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

标签 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')

我期望输出是:

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/

相关文章:

python - 在pygame应用程序中显示文本文件中的单词

python - 从源 : Pycharm doesn't get autocomplete information 构建的 OpenCV

Python - 将相邻元素分组到列表中的元组中?

javascript - 加载前两个图表时加载图表

c# - 在 C# 中对字符串数组进行插入排序

python - 如果图例在轴外,则在单击鼠标时注册双事件

java - 放置双值二维数组读取文本

javascript - 在Javascript中动态地将多个对象存储在数组中

MySQL 排序 : how to make Cyrillic characters go before Latin characters?

php - Math & php : FAST sort of an array [1. .N] 以一种特殊的方式