我在对以数字作为字符串的 numpy 数组进行排序时遇到问题。我需要将它们保留为字符串,因为整数后面还有其他单词。
它以相反的顺序对负数进行排序:
>>> import numpy as np
>>> a = np.array(["3", "-2", "-1", "0", "2"])
>>> a.sort()
>>> a
array(['-1', '-2', '0', '2', '3'], dtype='|S2')
我期望输出是:
array(['-2', '-1', '0', '2', '3'], dtype='|S2')
有什么建议吗?
最佳答案
你可以使用 natural sorting :
import numpy as np
import re
def atoi(text):
try:
return int(text)
except ValueError:
return text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
'''
return [ atoi(c) for c in re.split('([-]?\d+)', text) ]
a = np.array(["3", "-2", "-1", "0", "2", "word"])
print(sorted(a,key=natural_keys))
# ['-2', '-1', '0', '2', '3', 'word']
a = np.array(["3", "-2", "-1", "0", "2", "word", "-1 word", "-2 up"])
print(sorted(a,key=natural_keys))
# ['-2', '-2 up', '-1', '-1 word', '0', '2', '3', 'word']
关于python - 用负数对 numpy 字符串数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7638738/