【问题标题】:Sort rows of a 2D array, based on the first column根据第一列对二维数组的行进行排序
【发布时间】:2019-08-09 17:27:20
【问题描述】:

我想在 Python 3 中根据第一列的元素对二维数组的行进行排序。例如,如果

    x = array([[ 5. ,  9. ,  2. ,  6. ],
               [ 7. , 12. ,  3.5,  8. ],
               [ 2. ,  6. ,  7. ,  9. ]])

那么我需要排序后的数组是

    x = array([[ 2. ,  6. ,  7. ,  9. ],
               [ 5. ,  9. ,  2. ,  6. ],
               [ 7. , 12. ,  3.5,  8. ]])

我该怎么做? here 提出并回答了类似的问题,但它对我不起作用。

【问题讨论】:

  • 如果我的回答适合你,请考虑acceptingit

标签: python arrays python-3.x sorting


【解决方案1】:

以下应该有效:

import numpy as np
x = np.array([[ 5. ,  9. ,  2. ,  6. ],
               [ 7. , 12. ,  3.5,  8. ],
               [ 2. ,  6. ,  7. ,  9. ]])

x[x[:, 0].argsort()]
Out[2]:
array([[ 2. ,  6. ,  7. ,  9. ],
       [ 5. ,  9. ,  2. ,  6. ],
       [ 7. , 12. ,  3.5,  8. ]])

文档:numpy.argsort

【讨论】:

    【解决方案2】:
    #using sorted    
    x = ([[5.,9.,2.,6. ], [7.,12.,3.5,8.], [2.,6.,7.,9.]])
    x = sorted(x, key=lambda i: i[0]) #1st col 
    print(x)
    

    【讨论】:

      猜你喜欢
      • 2018-08-17
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 2015-06-08
      相关资源
      最近更新 更多