Sorting arrays in NumPy by column

后端 未结 13 2552
既然无缘
既然无缘 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:30

    Here is another solution considering all columns (more compact way of J.J's answer);

    ar=np.array([[0, 0, 0, 1],
                 [1, 0, 1, 0],
                 [0, 1, 0, 0],
                 [1, 0, 0, 1],
                 [0, 0, 1, 0],
                 [1, 1, 0, 0]])
    

    Sort with lexsort,

    ar[np.lexsort(([ar[:, i] for i in range(ar.shape[1]-1, -1, -1)]))]
    

    Output:

    array([[0, 0, 0, 1],
           [0, 0, 1, 0],
           [0, 1, 0, 0],
           [1, 0, 0, 1],
           [1, 0, 1, 0],
           [1, 1, 0, 0]])
    

提交回复
热议问题