Sort table data
Sorting is a common operation in data analysis, and Deephaven makes it easy to sort data in a variety of ways. This guide will show you how to sort table data programmatically.
You can also sort columns by right-clicking the column header in the UI.
sort
and sortDescending
You can sort table data programmatically by using the sort
and sortDescending
methods:
source = newTable(stringCol("Letter", "A", "B", "A", "B", "B", "A"), intCol("Number", 6, 6, 1, 3, 4, 4), stringCol("Color", "red", "blue", "orange", "purple", "yellow", "pink"))
resultSort = source.sort("Letter")
resultSortDesc = source.sortDescending("Letter")
- resultSort
- resultSortDesc
Given a column name to order the data by, sort
returns a new table with the data sorted in ascending (A-Z) order, and sortDescending
returns a new table with the data sorted in descending (Z-A) order.
Sorting by multiple columns
Both sort
and sortDescending
can sort multiple columns at once. For example, here we will sort the table from the previous example by our Letter
column, then the Number
column.
resultSort = source.sort("Letter", "Number")
resultSortDesc = source.sortDescending("Letter", "Number")
- resultSort
- resultSortDesc
Complex sorts
The sort
method can be used to sort multiple columns in different directions. For example, we can sort by Letter
in ascending order, then by Number
in descending order.
sortColumns = [
SortColumn.asc(ColumnName.of("Letter")),
SortColumn.desc(ColumnName.of("Number"))
]
result = source.sort(sortColumns)
- result
This is simpler than invoking both methods to accomplish the same result:
result = source.sort("Letter").sortDescending("Number")
- result
restrictSortTo
The restrictSortTo
method allows you to restrict the columns that can be sorted via the UI. This is useful if you want to prevent yourself or other users from accidentally performing expensive sort operations as you interact with tables in the UI. For example, we can restrict sorting to the Letter
column:
table = source.restrictSortTo("Letter")
- table
Now, we can still sort by Letter
, but attempting to sort by Number
will result in an error:
tSorted = table.sort("Number")