如何按一列字典顺序对 2D numpy 数组进行排序?
How to sort a 2D numpy array lexicographically by one column?
如何对具有 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 列进行词法排序,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]]
应该屈服
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]]
如何对具有 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 列进行词法排序,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]]
应该屈服
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]]