Sha*_*ane 1 python arrays sorting numpy
我在排序一个数字为字符串的numpy数组时遇到问题.我需要将它们保存为字符串,因为整数后面还有其他单词.
它以相反的顺序排序负数:
>>> import numpy as np
>>> a = np.array(["3", "-2", "-1", "0", "2"])
>>> a.sort()
>>> a
array(['-1', '-2', '0', '2', '3'], dtype='|S2')
Run Code Online (Sandbox Code Playgroud)
我原以为输出是:
array(['-2', '-1', '0', '2', '3'], dtype='|S2')
Run Code Online (Sandbox Code Playgroud)
有什么建议?
你可以使用自然分类:
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']
Run Code Online (Sandbox Code Playgroud)