如何根据列值对numpy数组进行排序?

时间:2017-10-29 01:01:04

标签: python numpy

我有一个看起来像这样的numpy数组:

>>> array_text[:10]
array([[1, 52.51, 12, 0],
    [1, 52.52, 52, 2],
    [1, 52.53, 1, 6],
    [2, 52.51, 20, 0],
    [2, 52.52, 75, 76],
    [2, 52.53, 6, 33],
    [3, 52.51, 84, 0],
    [3, 52.52, 39, 68],
    [3, 52.53, 0, 13],
    [4, 52.51, 1, 0]], dtype=object)

我想要做的是按照第二列按降序对其进行排序。所以我想要的结果是:

>>> array_text[:10]
array([[1, 52.53, 1, 6],
    [1, 52.52, 52, 2],
    [1, 52.51, 12, 0],
    [2, 52.53, 6, 33],
    [2, 52.52, 75, 76],
    [2, 52.51, 20, 0],
    [3, 52.53, 0, 13],
    [3, 52.52, 39, 68],
    [3, 52.51, 84, 0],
    [4, 52.51, 1, 0]], dtype=object)

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以使用numpy.lexsort。这里反转列的技巧是乘以-1。

import numpy as np
arr[np.lexsort((-1*arr[:,1], arr[:,0]))]

输出继电器:

array([[1, 52.53, 1, 6],
       [1, 52.52, 52, 2],
       [1, 52.51, 12, 0],
       [2, 52.53, 6, 33],
       [2, 52.52, 75, 76],
       [2, 52.51, 20, 0],
       [3, 52.53, 0, 13],
       [3, 52.52, 39, 68],
       [3, 52.51, 84, 0],
       [4, 52.51, 1, 0]], dtype=object)

答案 1 :(得分:0)

处理此问题的最简单方法是使用pandas,因为该功能已使用sort_values方法内置到数据框中。

import pandas as pd
import numpy as np

x = np.array([[1, 52.51, 12, 0],
              [1, 52.52, 52, 2],
              [1, 52.53, 1, 6],
              [2, 52.51, 20, 0],
              [2, 52.52, 75, 76],
              [2, 52.53, 6, 33],
              [3, 52.51, 84, 0],
              [3, 52.52, 39, 68],
              [3, 52.53, 0, 13],
              [4, 52.51, 1, 0]], dtype=object)

df = pd.DataFrame(x, columns=list('ABCD'))
df.sort_values(['A', 'B'], ascending=[True, False]).values
# returns:
array([[1, 52.53, 1, 6],
       [1, 52.52, 52, 2],
       [1, 52.51, 12, 0],
       [2, 52.53, 6, 33],
       [2, 52.52, 75, 76],
       [2, 52.51, 20, 0],
       [3, 52.53, 0, 13],
       [3, 52.52, 39, 68],
       [3, 52.51, 84, 0],
       [4, 52.51, 1, 0]], dtype=object)