Sorting arrays in NumPy by column

user248237 picture user248237 · May 13, 2010 · Viewed 339.8k times · Source

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]])

Answer

Steve Tjoa picture Steve Tjoa · May 13, 2010

I suppose this works: a[a[:,1].argsort()]

This indicates the second column of a and sort it based on it accordingly.