按多个轴对2D numpy数组排序 [英] Sorting a 2D numpy array by multiple axes
问题描述
我有一个形状为(N,2)的2D numpy数组,其中包含N个点(x和y坐标).例如:
I have a 2D numpy array of shape (N,2) which is holding N points (x and y coordinates). For example:
array([[3, 2],
[6, 2],
[3, 6],
[3, 4],
[5, 3]])
我想对它进行排序,以使我的点按x坐标排序,然后在x坐标相同的情况下按y排序.因此,上面的数组应如下所示:
I'd like to sort it such that my points are ordered by x-coordinate, and then by y in cases where the x coordinate is the same. So the array above should look like this:
array([[3, 2],
[3, 4],
[3, 6],
[5, 3],
[6, 2]])
如果这是一个普通的Python列表,我将简单地定义一个比较器来执行我想要的操作,但是据我所知,numpy的sort函数不接受用户定义的比较器.有什么想法吗?
If this was a normal Python list, I would simply define a comparator to do what I want, but as far as I can tell, numpy's sort function doesn't accept user-defined comparators. Any ideas?
感谢您的想法!我建立了一个具有1000000个随机整数点的快速测试用例,并对可以运行的基准点进行了基准测试(对不起,目前无法升级numpy).
Thanks for the ideas! I set up a quick test case with 1000000 random integer points, and benchmarked the ones that I could run (sorry, can't upgrade numpy at the moment).
Mine: 4.078 secs
mtrw: 7.046 secs
unutbu: 0.453 secs
推荐答案
使用
由于 Since 这篇关于按多个轴对2D numpy数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
如果a
是C_CONTIGUOUS
,则a.ravel()
返回一个视图.如果是这样的话
@ars的方法(通过使用ravel
而不是flatten
进行了稍微修改)产生了对a
进行排序的好方法就地:
a.ravel()
returns a view if a
is C_CONTIGUOUS
. If that is true,
@ars's method, slightly modifed by using ravel
instead of flatten
, yields a nice way to sort a
in-place:a = np.array([(3, 2), (6, 2), (3, 6), (3, 4), (5, 3)])
dt = [('col1', a.dtype),('col2', a.dtype)]
assert a.flags['C_CONTIGUOUS']
b = a.ravel().view(dt)
b.sort(order=['col1','col2'])
b
是a
的视图,因此对b
进行排序也对a
进行排序:b
is a view of a
, sorting b
sorts a
as well:print(a)
# [[3 2]
# [3 4]
# [3 6]
# [5 3]
# [6 2]]