在numpy中使用多个排序键排序

aes*_*vex 6 python arrays sorting numpy

我没有在SO上找到这个答案,所以我在这里分享:

问题:当有多个排序键时,如何在matlab中模拟sortrows功能?在matlab中,这看起来像是:

sortrows(x,[3,-4])
Run Code Online (Sandbox Code Playgroud)

首先按第3列排序,然后按第2列排序.

如果按一列排序,可以使用np.argsort查找该列的索引,并应用这些索引.但是你如何为多列做到这一点?

aes*_*vex 5

语法非常笨拙,看起来很奇怪,但最干净的做法是np.lexsort.

data = np.array([[3, 0, 0, .24],
                 [4, 1, 1, .41],
                 [2, 1, 1, .63],
                 [1, 1, 3, .38]]) #imagine rows of a spreadsheet
#now do sortrows(data,[3,-4])
ix = np.lexsort((data[:, 3][::-1], data[:, 2])) 
#this yields [0, 2, 1, 3]

#note that lexsort sorts first from the last row, so sort keys are in reverse order

data[ix]
Run Code Online (Sandbox Code Playgroud)