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]])
You can sort on multiple columns as per Steve Tjoa's method by using a stable sort like mergesort and sorting the indices from the least significant to the most significant columns:
This sorts by column 0, then 1, then 2.
I suppose this works:
a[a[:,1].argsort()]
This indicates the second column of
a
and sort it based on it accordingly.From the NumPy mailing list, here's another solution: