根据行逐步对Numpy Python矩阵进行排序 [英] Sort a Numpy Python matrix progressively according to rows

查看:103
本文介绍了根据行逐步对Numpy Python矩阵进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我四处搜寻并试图找到似乎简单的问题的解决方案,但没有提出任何建议.问题是逐步根据矩阵的列对矩阵进行排序.因此,如果我有一个类似numpy的矩阵:

I have searched around and tried to find a solution to what seems to be a simple problem, but have come up with nothing. The problem is to sort a matrix based on its columns, progressively. So, if I have a numpy matrix like:

import numpy as np
X=np.matrix([[0,0,1,2],[0,0,1,1],[0,0,0,4],[0,0,0,3],[0,1,2,5]])
print(X)
[[0 0 1 2]
 [0 0 1 1]
 [0 0 0 4]
 [0 0 0 3]
 [0 1 2 5]]

我想根据第一列对其进行排序,然后对第二,第三等进行排序,以获得类似以下结果:

I would like to sort it based on the first column, then the second, the third, and so on, to get a result like:

Xsorted=np.matrix([[0,0,0,3],[0,0,0,4],[0,0,1,1],[0,0,1,2],[0,1,2,5]])
print(Xsorted)
[[0,0,0,3]
 [0,0,0,4]
 [0,0,1,1]
 [0,0,1,2]
 [0,1,2,5]]

虽然我认为可以通过命名列和所有类似的东西来对矩阵进行排序,但我更希望有一种排序方法,该方法与矩阵的大小无关.我正在使用Python 3.4,如果那很重要的话.

While I think it is possible to sort a matrix like this by naming the columns and all that, I would prefer to have a method for sorting that doesn't depend so much on how big the matrix is. I am using Python 3.4, if that is important.

任何帮助将不胜感激!

推荐答案

它不会特别快,但是您始终可以将行转换为元组,然后使用Python的sort:

It's not going to be particularly fast, but you can always convert your rows to tuples, then use Python's sort:

np.matrix(sorted(map(tuple, X.A)))

您也可以使用np.lexsort,如此答案尽管您应该使用实际数据进行测试以确保:

The lexsort approach appears to be faster, though you should test with your actual data to make sure:

In [20]: X = np.matrix(np.random.randint(10, size=(100,100)))

In [21]: %timeit np.matrix(sorted(map(tuple, X.A)))
100 loops, best of 3: 2.23 ms per loop

In [22]: %timeit X[np.lexsort(X.T[::-1])]
1000 loops, best of 3: 1.22 ms per loop

这篇关于根据行逐步对Numpy Python矩阵进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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