gpt4 book ai didi

python - 用负数对 numpy 字符串数组进行排序?

转载 作者:太空宇宙 更新时间:2023-11-04 07:24:25 25 4
gpt4 key购买 nike

我在对以数字作为字符串的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com