你可以使用np.lexsort:
numpy.lexsort(keys, axis=-1)
使用键序列执行间接排序。
给定多个排序键,可以解释为
在电子表格中,lexsort 返回一个整数索引数组
描述多列的排序顺序。
In [13]: data = np.matrix(np.arange(10)[::-1].reshape(-1,2))
In [14]: data
Out[14]:
matrix([[9, 8],
[7, 6],
[5, 4],
[3, 2],
[1, 0]])
In [15]: temp = data.view(np.ndarray)
In [16]: np.lexsort((temp[:, 1], ))
Out[16]: array([4, 3, 2, 1, 0])
In [17]: temp[np.lexsort((temp[:, 1], ))]
Out[17]:
array([[1, 0],
[3, 2],
[5, 4],
[7, 6],
[9, 8]])
请注意,如果您将多个键传递给np.lexsort,则 last 键是主键。倒数第二个键是第二个键,以此类推。
使用上面显示的np.lexsort 需要使用临时数组,因为np.lexsort 不适用于numpy 矩阵。自从
temp = data.view(np.ndarray) 创建一个视图,而不是 data 的副本,它不需要太多额外的内存。不过,
temp[np.lexsort((temp[:, 1], ))]
是一个新数组,确实需要更多内存。
还有一种按列就地排序的方法。这个想法是将数组视为具有两列的结构化数组。与普通的 ndarray 不同,结构化数组有一个 sort 方法,它允许您将列指定为键:
In [65]: data.dtype
Out[65]: dtype('int32')
In [66]: temp2 = data.ravel().view('int32, int32')
In [67]: temp2.sort(order = ['f1', 'f0'])
请注意,由于temp2 是data 的视图,它不需要分配新内存和复制数组。另外,排序temp2同时修改data:
In [69]: data
Out[69]:
matrix([[1, 0],
[3, 2],
[5, 4],
[7, 6],
[9, 8]])