[英]How do I sort a 2D numpy array in this specific way
I realize there are quite a number of 'how to sort numpy array'-questions on here already. 我意识到这里已经有很多“如何对numpy数组进行排序”的问题。 But I could not find how to do it in this specific way.
但是我找不到如何以这种特定方式进行操作。
I have an array similar to this: 我有一个与此类似的数组:
array([[1,0,1,],
[0,0,1],
[1,1,1],
[1,1,0]])
I want to sort the rows, keeping the order within the rows the same. 我想对行进行排序,使行内的顺序保持不变。 So I expect the following output:
所以我期望以下输出:
array([[0,0,1,],
[1,0,1],
[1,1,0],
[1,1,1]])
You can use dot
and argsort
: 您可以使用
dot
和argsort
:
a[a.dot(2**np.arange(a.shape[1])[::-1]).argsort()]
# array([[0, 0, 1],
# [1, 0, 1],
# [1, 1, 0],
# [1, 1, 1]])
The idea is to convert the rows into integers. 这个想法是将行转换为整数。
a.dot(2**np.arange(a.shape[1])[::-1])
# array([5, 1, 7, 6])
Then, find the sorted indices and use that to reorder a
: 然后,找到排序后的索引,并使用它对
a
进行重新排序:
a.dot(2**np.arange(a.shape[1])[::-1]).argsort()
# array([1, 0, 3, 2])
My tests show this is slightly faster than lexsort
. 我的测试表明,这比
lexsort
快一点。
a = a.repeat(1000, axis=0)
%timeit a[np.lexsort(a.T[::-1])]
%timeit a[a.dot(2**np.arange(a.shape[1])[::-1]).argsort()]
230 µs ± 18.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
192 µs ± 4.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Verify correctness: 验证正确性:
np.array_equal(a[a.dot(2**np.arange(a.shape[1])[::-1]).argsort()],
a[np.lexsort(a.T[::-1])])
# True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.