首頁  >  問答  >  主體

python3.x - python中有沒有直接對多維數組排序的方法?

如何依第一列的降序排列如下數組:

dl1 = numpy.array([[ 0.02598003,1.],
                   [ 0.00730082,2.],
                   [ 0.05471569,3.],
                   [ 0.02599167,4.],
                   [ 0.0544947 ,5.],
                   [ 0.00753346,6.]])

網路上其他地方說直接dl1.sort()會預設按第一列排序,但好像不行

習慣沉默習慣沉默2681 天前618

全部回覆(4)我來回復

  • 迷茫

    迷茫2017-05-18 10:55:30

    雷雷

    回覆
    0
  • 黄舟

    黄舟2017-05-18 10:55:30

    >>> a=np.array([[ 0.02598003,1.],
                   [ 0.00730082,2.],
                   [ 0.05471569,3.],
                   [ 0.02599167,4.],
                   [ 0.0544947 ,5.],
                   [ 0.00753346,6.]])
    >>> a.sort(0)
    >>> a
    array([[ 0.00730082,  1.        ],
           [ 0.00753346,  2.        ],
           [ 0.02598003,  3.        ],
           [ 0.02599167,  4.        ],
           [ 0.0544947 ,  5.        ],
           [ 0.05471569,  6.        ]])
    >>> 

    np.sort 是把各維分別排序的

    如果你是要二維組的聯合排序,要用np.argsort方法

    >>> a=np.array([[ 0.02598003,1.],
                   [ 0.00730082,2.],
                   [ 0.05471569,3.],
                   [ 0.02599167,4.],
                   [ 0.0544947 ,5.],
                   [ 0.00753346,6.]])
    
    >>> a[a.argsort(0)[:,0]]
    array([[ 0.00730082,  2.        ],
           [ 0.00753346,  6.        ],
           [ 0.02598003,  1.        ],
           [ 0.02599167,  4.        ],
           [ 0.0544947 ,  5.        ],
           [ 0.05471569,  3.        ]])
    >>> 

    如果數據很多的話,用python內部的 sorted會降低效率

    回覆
    0
  • 迷茫

    迷茫2017-05-18 10:55:30

    雷雷

    回覆
    0
  • 为情所困

    为情所困2017-05-18 10:55:30

    dl1.sort(axis=0)

    ndarray.sort的关键字参数axis就是用來依照某列排序

    axis : int, optional

    Axis along which to sort. Default is -1, which means sort along the last axis.

    回覆
    0
  • 取消回覆