使用lexsort对numpy数组进行排序.替代pandas的sort_values



我希望b的顺序等于下面a的结果。

b的结果不是我所期望的。我认为它将按升序按列排序,但我认为我误解了lexsort的工作原理。

我的目标是能够按照下面的df排序的方式排序数组。我使用lexsort,因为我认为这将是最好的东西,用于一个数组,也包含分类值。

import numpy as np
import pandas as pd
x = np.array([[1,2],[1,3],[1,4],[2,1],[2,2],[2,3],[2,4],[0,1],[1,0],[0,2]])
a=pd.DataFrame(x).sort_values(by=[0,1], ascending=[0,1])
b=x[np.lexsort((x[:,1],x[:,0][::-1]))]
print(a)
print(b)

从文档中,它应该是last, first来获得排序顺序:

sorter = np.lexsort((x[:, 1], x[:, 0]))
x[sorter][::-1] # sorting in descending order
Out[899]: 
array([[2, 4],
[2, 3],
[2, 2],
[2, 1],
[1, 4],
[1, 3],
[1, 2],
[1, 0],
[0, 2],
[0, 1]])

要模拟一端降序,另一端升序,您可以将np.unique,np.splitnp.concatenate组合在一起:

temp = x[sorter]
_, s = np.unique(temp[:, 0], return_counts=True)
np.concatenate(np.split(temp, s.cumsum())[::-1])
Out[972]: 
array([[2, 1],
[2, 2],
[2, 3],
[2, 4],
[1, 0],
[1, 2],
[1, 3],
[1, 4],
[0, 1],
[0, 2]])