我有以下代码:
import numpy as np
a = np.array([["value1", "value2", 3, "value4", "value5"],
["value1", "value2", -10, "value4", "value5"],
["value1", "value2", 31, "value4", "value5"],
["value1", "value2", 5, "value4", "value5"],
["value1", "value2", 3, "value4", "value5"]])
print("Default")
print(a)
a = a[a[:, 2].argsort()]
print()
print("Sorted:")
print(a)
这导致以下输出:
Sorted:
[['value1' 'value2' '-10' 'value4' 'value5']
['value1' 'value2' '3' 'value4' 'value5']
['value1' 'value2' '3' 'value4' 'value5']
['value1' 'value2' '31' 'value4' 'value5']
['value1' 'value2' '5' 'value4' 'value5']]
但我正在寻找的功能是输出这个:
Sorted:
[['value1' 'value2' '-10' 'value4' 'value5']
['value1' 'value2' '3' 'value4' 'value5']
['value1' 'value2' '3' 'value4' 'value5']
['value1' 'value2' '5' 'value4' 'value5']
['value1' 'value2' '31' 'value4' 'value5']]
当我将31值更改为51时,它会正确输出。所以numpy基本上是对数字的第一个字符进行排序。但我找不到如何对整个数字进行排序。
答案 0 :(得分:4)
如评论中所述,您要排序的值是字符串。变化
a = a[a[:, 2].argsort()]
到
a = a[a[:, 2].astype(np.int).argsort()]
因此将它们作为整数进行比较。
答案 1 :(得分:1)
您必须将第三列转换为整数。
看这里:
a = ['5']
b = ['31']
if a[0] > b[0]:
print("{} is bigger than {}".format(a[0], b[0]))
Out[0]: 5 is bigger than 31
a = int(a[0])
b = int(b[0])
if b > a:
print("{} is bigger than {}".format(b, a))
Out[1]: 31 is bigger than 5
出于这个原因,请按照:
import numpy as np
a = np.array('your array')
a = a[a[:, 2].astype(np.int).argsort()]