排序numpy的字符串数组负数? [英] Sort numpy string array with negative numbers?

查看:185
本文介绍了排序numpy的字符串数组负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在整理有数字作为一个字符串数组numpy的一个问题。我需要保持这些字符串,因为有整数后等字样。

I'm having a problem sorting a numpy array that has numbers as strings. I need to keep these as strings because there are other words after the integers.

它的排序负数以相反的顺序:

It's sorting negative numbers in reverse order:

>>> import numpy as np
>>> a = np.array(["3", "-2", "-1", "0", "2"])
>>> a.sort()
>>> a
array(['-1', '-2', '0', '2', '3'], dtype='|S2')

我本来期望的输出是:

I would have expected the output to be:

array(['-2', '-1', '0', '2', '3'], dtype='|S2')

有什么建议?

推荐答案

您可以使用自然排序

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']

这篇关于排序numpy的字符串数组负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆