如何按字典顺序对一列2D numpy数组进行排序?

时间:2017-09-18 23:53:58

标签: python arrays sorting numpy lexicographic

如何使用2个元素对numpy 2D数组进行排序: 例如,我有:

[['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,但它不起作用! 任何帮助将不胜感激

2 个答案:

答案 0 :(得分:3)

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

out = x[np.argsort(x[:, 0])[::-1]]
print(out)
array([['0.6435256766173603', 'some text'],
       ['0.017696632827641112', 'some text3'],
       ['0.013180497307149886', 'some text2']],

答案 1 :(得分:3)

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]]