numpy中具有多个排序键的排序行 [英] Sortrows with multiple sorting keys in numpy

查看:130
本文介绍了numpy中具有多个排序键的排序行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I haven't found this answer on SO, so I am sharing it here:

问题:当有多个排序键时,如何在matlab中模拟排序行功能?在matlab中,例如:

Question: How do you emulate sortrows functionality in matlab when there are multiple sorting keys? In matlab, this looks like e.g.:

sortrows(x,[3,-4])

首先按第三列排序,然后按第二列排序.

which sorts first by the 3rd column and then by the second column.

如果按一列排序,则可以使用np.argsort查找该列的索引,然后应用这些索引.但是,如何对多列进行处理呢?

If you were sorting by one column, you could use np.argsort to find the indices of that column, and apply those indices. But how do you do it for multiple columns?

推荐答案

语法非常笨拙,看起来很怪异,但最干净的方法是

The syntax is quite unwieldy and looks weird, but the cleanest thing to do is 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]

这篇关于numpy中具有多个排序键的排序行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆