Sorting arrays in NumPy by column

后端 未结 13 2534
既然无缘
既然无缘 2020-11-22 03:47

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

13条回答
  •  我在风中等你
    2020-11-22 04:21

    It is an old question but if you need to generalize this to a higher than 2 dimension arrays, here is the solution than can be easily generalized:

    np.einsum('ij->ij', a[a[:,1].argsort(),:])
    

    This is an overkill for two dimensions and a[a[:,1].argsort()] would be enough per @steve's answer, however that answer cannot be generalized to higher dimensions. You can find an example of 3D array in this question.

    Output:

    [[7 0 5]
     [9 2 3]
     [4 5 6]]
    

提交回复
热议问题