Sorting arrays in NumPy by column

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

    A little more complicated lexsort example - descending on the 1st column, secondarily ascending on the 2nd. The tricks with lexsort are that it sorts on rows (hence the .T), and gives priority to the last.

    In [120]: b=np.array([[1,2,1],[3,1,2],[1,1,3],[2,3,4],[3,2,5],[2,1,6]])
    In [121]: b
    Out[121]: 
    array([[1, 2, 1],
           [3, 1, 2],
           [1, 1, 3],
           [2, 3, 4],
           [3, 2, 5],
           [2, 1, 6]])
    In [122]: b[np.lexsort(([1,-1]*b[:,[1,0]]).T)]
    Out[122]: 
    array([[3, 1, 2],
           [3, 2, 5],
           [2, 1, 6],
           [2, 3, 4],
           [1, 1, 3],
           [1, 2, 1]])
    

提交回复
热议问题