2017-09-18 58 views
0

如何排序numpy的二維數組與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,但它不工作! 任何幫助將不勝感激

+0

你有*串的'numpy.ndarray' *?你應該使用普通的Python列表... –

回答

2

假設你想你的數組lexsorted第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']], 
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]] 
+0

重複的:https://stackoverflow.com/a/46289813/4909087 –