Skip to content

Sorting

Order the rows of a table. These methods are available on pykx.Table and pykx.KeyedTable objects.

sort_values

sort_values(by=None, ascending=True)

Sort the table by the values of one or more columns.

Parameters:

Name Type Description Default
by str or list

The name of the column, or list of names, to sort by. If not given all columns are used.

None
ascending bool

Sort in ascending order if True and descending order if False.

True

Returns:

Type Description
Table

The sorted table.

Examples:

>>> tab = kx.q('([] a:3 1 2; b:4 5 6)')
>>> tab.sort_values('a')
pykx.Table(pykx.q('
a b
---
1 5
2 6
3 4
'))
>>> tab.sort_values('a', ascending=False)
pykx.Table(pykx.q('
a b
---
3 4
2 6
1 5
'))

nlargest

nlargest(n, columns=None, keep='first')

Return the first n rows ordered by the columns in descending order.

Parameters:

Name Type Description Default
n int

The number of rows to return.

required
columns str or list

The name of the column, or list of names, to order by.

None
keep str

How to handle duplicate values, one of 'first', 'last' or 'all'.

'first'

Returns:

Type Description
Table

The first n rows of the table in descending order.

Examples:

>>> tab = kx.q('([] a:3 1 2; b:4 5 6)')
>>> tab.nlargest(2, 'a')
pykx.Table(pykx.q('
a b
---
3 4
2 6
'))

nsmallest

nsmallest(n, columns, keep='first')

Return the first n rows ordered by the columns in ascending order.

Parameters:

Name Type Description Default
n int

The number of rows to return.

required
columns str or list

The name of the column, or list of names, to order by.

required
keep str

How to handle duplicate values, one of 'first', 'last' or 'all'.

'first'

Returns:

Type Description
Table

The first n rows of the table in ascending order.

Examples:

>>> tab = kx.q('([] a:3 1 2; b:4 5 6)')
>>> tab.nsmallest(2, 'a')
pykx.Table(pykx.q('
a b
---
1 5
2 6
'))