[英]How to sort a 2D numpy array lexicographically by one column?
how to sort numpy 2D array with 2 elements: For example I have: 如何用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']]
I tried np.argsort, np.sort, but it doesn't work! 我尝试了np.argsort,np.sort,但没有用! Any help will be appreciated
任何帮助将不胜感激
Assuming you want your array lexsorted by the 0th column, np.argsort
is what you want. 假设您要按第0列对数组进行lexsort排序,则需要
np.argsort
。
out = x[np.argsort(x[:, 0])[::-1]]
print(out)
array([['0.6435256766173603', 'some text'],
['0.017696632827641112', 'some text3'],
['0.013180497307149886', 'some text2']],
a = np.array([['0.6435256766173603', 'some text'],
['0.013180497307149886', 'some text2'],
['0.017696632827641112', 'some text3']])
a[a[:, 0].argsort()[::-1]]
should yield 应该屈服
array([['0.6435256766173603', 'some text'],
['0.017696632827641112', 'some text3'],
['0.013180497307149886', 'some text2']],
dtype='|S20')
Breaking it down: 分解:
# 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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.