按列对NumPy浮点数组进行排序 [英] Sort NumPy float array column by column
问题描述
遵循此技巧,它可以获取NumPy数组的唯一条目,现在有一个两列数组,基本上是成对的,第一个元素的范围为[0.9:0.02:1.1],第二个元素的范围为[1.5:0.1:2.0].我们将此称为A
.目前,它是完全未分类的,即
Following this trick to grab unique entries for a NumPy array, I now have a two-column array, basically of pairs with first element in the range [0.9:0.02:1.1] and the second element in the range [1.5:0.1:2.0]. Let's call this A
. Currently, it's completely unsorted, i.e.
In [111]: A
Out[111]:
array([[ 1.1 , 1.9 ],
[ 1.06, 1.9 ],
[ 1.08, 1.9 ],
[ 1.08, 1.6 ],
[ 0.9 , 1.8 ],
...
[ 1.04, 1.6 ],
[ 0.96, 2. ],
[ 0.94, 2. ],
[ 0.98, 1.9 ]])
我想对它进行排序,以使每一行都在第二列中增加,然后在第一列中增加.即
I'd like to sort it so that each row first increases in the second column, then the first. i.e.
array([[ 0.9 , 1.5 ],
[ 0.9 , 1.6 ],
[ 0.9 , 1.7 ],
[ 0.9 , 1.9 ],
[ 0.9 , 1.9 ],
[ 0.9 , 2. ],
[ 0.92, 1.5 ],
...
[ 1.08, 2. ],
[ 1.1 , 1.5 ],
[ 1.1 , 1.6 ],
[ 1.1 , 1.7 ],
[ 1.1 , 1.8 ],
[ 1.1 , 1.9 ],
[ 1.1 , 2. ]])
但是我找不到同时提供两者的排序算法.根据建议的此处,我尝试了A[A[:,0].argsort()]
和A[A[:,1].argsort()]
,但它们仅对一列进行排序.我也尝试过同时使用这两种方法,但同样的事情也会发生.
but I can't find a sort algorithm that gives both. As suggested here, I've tried A[A[:,0].argsort()]
and A[A[:,1].argsort()]
, but they only sort one column each. I've also tried applying both but the same thing happens.
如果我错过了一些简单的事情,我深表歉意,但是我已经找了一段时间了...
I apologize if I've missed something simple but I've been looking for this for a while now...
推荐答案
numpy.lexsort
将在这里工作:
numpy.lexsort
will work here:
A[np.lexsort(A.T)]
在将A
传递给lexsort之前,需要进行转置,因为在传递2d数组时,它希望按行(最后一行,倒数第二行等)进行排序.
You need to transpose A
before passing it to lexsort because when passed a 2d array it expects to sort by rows (last row, second last row, etc).
另一种可能稍微清晰的方法是显式传递列:
The alternative possibly slightly clearer way is to pass the columns explicitly:
A[np.lexsort((A[:, 0], A[:, 1]))]
您仍然需要记住lexsort首先按最后一个键排序(这可能有一定的道理;这与对连续键执行稳定排序相同).
You still need to remember that lexsort sorts by the last key first (there's probably some good reason for this; it's the same as performing a stable sort on successive keys).
这篇关于按列对NumPy浮点数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!