本文介绍了按字典顺序排序2d numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大型的二维数组,其中包含数百列.我想按字典顺序对其进行排序,即按第一列,然后按第二列,依此类推,直到最后一列.我想这应该很容易做到,但是我还没有找到一种快速的方法.

I have a large 2d array with hundreds of columns. I would like to sort it lexicographically, i.e. 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.

推荐答案

这是 numpy.lexsort 用于,但界面很尴尬.将其传递给2D数组,它将对进行argsort排序,首先按 last 行排序,然后按倒数第二行进行,直到第一行:

This is what numpy.lexsort is for, but the interface is awkward. 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:

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

如果要按行排序,并以第一列为主键,则需要先旋转数组,然后再lexsort对其进行操作:

If you want to sort by rows, with the first column as the primary key, you need to rotate the array before lexsorting it:

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

这篇关于按字典顺序排序2d numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 02:24