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 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
a = a[::, a[0,].argsort()[::-1]]
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.