How can I sort an array in NumPy by the nth column?
For example,
a = array([[9, 2, 3],
[4, 5, 6],
[7, 0, 5]])
I'd like to sort rows by the second column, such that I get back:
array([[7, 0, 5],
[9, 2, 3],
[4, 5, 6]])
In case someone wants to make use of sorting at a critical part of their programs here's a performance comparison for the different proposals:
So, it looks like indexing with argsort is the quickest method so far...
@steve's is actually the most elegant way of doing it.
For the "correct" way see the order keyword argument of numpy.ndarray.sort
However, you'll need to view your array as an array with fields (a structured array).
The "correct" way is quite ugly if you didn't initially define your array with fields...
As a quick example, to sort it and return a copy:
To sort it in-place:
@Steve's really is the most elegant way to do it, as far as I know...
The only advantage to this method is that the "order" argument is a list of the fields to order the search by. For example, you can sort by the second column, then the third column, then the first column by supplying order=['f1','f2','f0'].
Here is another solution considering all columns (more compact way of J.J's answer);
Sort with lexsort,
Output:
From the Python documentation wiki, I think you can do:
The output is:
A little more complicated
lexsort
example - descending on the 1st column, secondarily ascending on the 2nd. The tricks withlexsort
are that it sorts on rows (hence the.T
), and gives priority to the last.I had a similar problem.
My Problem:
I want to calculate an SVD and need to sort my eigenvalues in descending order. But I want to keep the mapping between eigenvalues and eigenvectors. My eigenvalues were in the first row and the corresponding eigenvector below it in the same column.
So I want to sort a two-dimensional array column-wise by the first row in descending order.
My Solution
So how does this work?
a[0,]
is just the first row I want to sort by.Now I use argsort to get the order of indices.
I use
[::-1]
because I need descending order.Lastly I use
a[::, ...]
to get a view with the columns in the right order.