【问题标题】:How to sort a 2D numpy array lexicographically by one column?如何按一列按字典顺序对 2D numpy 数组进行排序?
【发布时间】:2017-09-18 23:53:58
【问题描述】:

如何对具有 2 个元素的 numpy 二维数组进行排序: 例如我有:

[['0.6435256766173603' 'some text']
 ['0.013180497307149886' 'some text2']
 ['0.017696632827641112' 'some text3']]  
I need:
[['0.6435256766173603' 'some text']
 ['0.017696632827641112' 'some text3']
 ['0.013180497307149886' 'some text2']] 

我尝试了 np.argsort、np.sort,但它不起作用! 任何帮助将不胜感激

【问题讨论】:

  • 你有一个带有字符串的numpy.ndarray?您可能应该只使用普通的 Python 列表...

标签: python arrays sorting numpy lexicographic


【解决方案1】:

假设您希望数组按第 0 列 lexsorted,np.argsort 就是您想要的。

out = x[np.argsort(x[:, 0])[::-1]]
print(out)

array([['0.6435256766173603', 'some text'],
       ['0.017696632827641112', 'some text3'],
       ['0.013180497307149886', 'some text2']],

【讨论】:

    【解决方案2】:
    a = np.array([['0.6435256766173603', 'some text'],
                  ['0.013180497307149886', 'some text2'],
                  ['0.017696632827641112', 'some text3']])
    
    a[a[:, 0].argsort()[::-1]]
    

    应该让步

    array([['0.6435256766173603', 'some text'],
           ['0.017696632827641112', 'some text3'],
           ['0.013180497307149886', 'some text2']],
          dtype='|S20')
    

    分解:

    # the first column of `a`
    a[:, 0]  
    
    # sorted indices of the first column, ascending order
    a[:, 0].argsort()  # [1, 2, 0]
    
    # sorted indices of the first column, descending order
    a[:, 0].argsort()[::-1]  # [0, 2, 1]
    
    # sort `a` according to the sorted indices from the last step
    a[a[:, 0].argsort()[::-1]]
    

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 2017-04-12
      • 2018-08-28
      • 1970-01-01
      相关资源
      最近更新 更多