简体   繁体   English

如何以这种特定方式对2D numpy数组进行排序

[英]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 : 您可以使用dotargsort

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.

相关问题 如何根据另一个2d numpy数组给定的索引对2d numpy数组的行进行排序 - How do I sort the rows of a 2d numpy array based on indices given by another 2d numpy array 如何将2D numpy数组转换为1D numpy数组的1D numpy数组? - How do I convert a 2D numpy array into a 1D numpy array of 1D numpy arrays? 如何将二维 numpy 数组与结构化数组合并 - How do I merge a 2d numpy array with a structured array "如何按条件提取 2D NumPy 数组的行?" - How do I extract rows of a 2D NumPy array by condition? 如何将一行2d numpy数组作为2d数组 - How do I get a row of a 2d numpy array as 2d array 对二维Numpy数组的特定子集进行计算的最高效/ Python方法 - Most Efficient/Pythonic Way to Do Calculations on a Specific Subset of a 2D Numpy Array 如何通过另一个 2d 索引数组对 2d numpy-array 的每一行进行排序? - How can I sort each row of the 2d numpy-array by another 2d index-array? 如何基于模式从 2D NumPy 数组中提取 2D NumPy 子数组? - How do I extract a 2D NumPy sub-array from a 2D NumPy array based on patterns? 如何使用 NumPy 通过 2D 数组以矢量化方式缩放一组 2D arrays(3D 数组)? - How can I scale a set of 2D arrays (3D array) by a 2D array in a vectorized way using NumPy? Pandas to_numpy() 生成列表数组。 如何从中获得 2D numpy 阵列? - Pandas to_numpy() results in an array of lists. How do I get a 2D numpy array from this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM