简体   繁体   English

按字典顺序排序2d numpy数组

[英]sort 2d numpy array lexicographically

I have a large 2d array with hundreds of columns. 我有一个包含数百列的大型2d数组。 I would like to sort it lexicographically, ie by first column, then by second column, and so on until the last column. 我想按字典顺序排序,即按第一列,然后按第二列,依此类推,直到最后一列。 I imagine this should be easy to do but I haven't been able to find a quick way to do this. 我想这应该很容易,但我找不到快速的方法来做到这一点。

This is what numpy.lexsort is for, but the interface is awkward. 这就是numpy.lexsort的用途,但界面很笨拙。 Pass it a 2D array, and it will argsort the columns , sorting by the last row first, then the second-to-last row, continuing up to the first row: 将它传递给一个2D数组,它将对列进行调整 ,首先按最后一行排序,然后排在倒数第二行,继续到第一行:

>>> x
array([[0, 0, 0, 2, 3],
       [2, 3, 2, 3, 2],
       [3, 1, 3, 0, 0],
       [3, 1, 1, 3, 1]])
>>> numpy.lexsort(x)
array([4, 1, 2, 3, 0], dtype=int64)

If you want to sort by rows, with the first column as the primary key, you need to rotate the array before lexsort ing it: 如果要按行排序,并将第一列作为主键,则需要在lexsort之前旋转数组:

>>> x[numpy.lexsort(numpy.rot90(x))]
array([[0, 0, 0, 2, 3],
       [2, 3, 2, 3, 2],
       [3, 1, 1, 3, 1],
       [3, 1, 3, 0, 0]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM