Sorting arrays in NumPy by column

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

    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:

    a = a[a[:,2].argsort()] # First sort doesn't need to be stable.
    a = a[a[:,1].argsort(kind='mergesort')]
    a = a[a[:,0].argsort(kind='mergesort')]
    

    This sorts by column 0, then 1, then 2.

提交回复
热议问题