多维Numpy数组排序

时间:2017-07-13 15:53:16

标签: python arrays sorting numpy multidimensional-array

我有(5,5)np.array如下。

>>> a
array([[23, 15, 11,  0, 17],
       [ 1,  2, 20,  4,  6],
       [16, 22,  8, 10, 18],
       [ 7, 12, 13, 14,  5],
       [ 3,  9, 21, 19, 24]])

我想对np.array进行多维排序,如下所示。

>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

为此,我做了,

  1. flatten()数组。
  2. 对拼合阵列进行排序。
  3. 重塑为(5,5)
  4. 在我的方法中,我觉得这是一个糟糕的编程习惯。是否有任何复杂的方法来完成这项任务? 谢谢。

    >>> a array([[23, 15, 11,  0, 17],
           [ 1,  2, 20,  4,  6],
           [16, 22,  8, 10, 18],
           [ 7, 12, 13, 14,  5],
           [ 3,  9, 21, 19, 24]])
    
    >>> a_flat = a.flatten()
    >>> a_flat
    array([23, 15, 11,  0, 17,  1,  2, 20,  4,  6, 16, 22,  8, 10, 18,  7, 12,
           13, 14,  5,  3,  9, 21, 19, 24])
    
    >>> a_sort = np.sort(a_flat)
    >>> a_sorted = a_sort.reshape(5,5)
    >>> a_sorted
    array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19],
           [20, 21, 22, 23, 24]])
    

1 个答案:

答案 0 :(得分:3)

我们可以使用np.ravel()获得展平视图,然后使用ndarray.sort()进行就地排序 -

a.ravel().sort()

将所有内容都放在原位,它可以避免创建任何临时数组并保持形状,从而避免重新整形。

示例运行 -

In [18]: a
Out[18]: 
array([[23, 15, 11,  0, 17],
       [ 1,  2, 20,  4,  6],
       [16, 22,  8, 10, 18],
       [ 7, 12, 13, 14,  5],
       [ 3,  9, 21, 19, 24]])

In [19]: a.ravel().sort()

In [20]: a
Out[20]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])