【问题标题】:Numpy Convert String to Float when PossibleNumpy 尽可能将字符串转换为浮点数
【发布时间】:2014-12-24 15:46:31
【问题描述】:

假设我有一个列表

mix = numpy.array(['1.', '2.', 'a'])

如何在可能的情况下将字符串转换为浮点数,以便获得:

array([1., 2., 'a'])

我尝试将try / exceptionastype() 一起使用,但它不会转换单个元素。

更新: 在csv 包中,有csv.QUOTE_NONNUMERIC,我想知道numpy 是否支持类似的东西。

【问题讨论】:

    标签: python string numpy floating-point


    【解决方案1】:

    没有找到让它工作的函数,所以我写了一些适合你的东西。

    def myArrayConverter(arr):
    
        convertArr = []
        for s in arr.ravel():    
            try:
                value = float32(s)
            except ValueError:
                value = s
    
            convertArr.append(value)
    
        return array(convertArr,dtype=object).reshape(arr.shape)
    

    干杯

    【讨论】:

    • 我试着找到一个现有的功能来做到这一点,但也不能......你的功能很好,但不是通用的。例如,不能处理二维数组。但是,请为您的及时回复投赞成票,伙计
    • 您好 Vindicate,您没有指定您想要适用于更多维度的东西。根据您的示例,之前给出的答案将非常适合您。没有太多调整,我编辑了解决方案,现在它适用于您想要的任意尺寸。希望对您有所帮助。
    • 真是好人,只是希望他们能开发一种条件转换的方法。
    【解决方案2】:

    对于混合数据类型的数组集dtype=object

    >>> mix = numpy.array(['1.', '2.', 'a'])
    >>> mixed=[]
    >>> for a in list(mix):
           try:
             mixed.append(float(a))
           except:
             mixed.append(a)
    
    >>> mixed=numpy.array(mixed, dtype=object)
    >>> mixed
    array([1.0, 2.0, 'a'], dtype=object)
    >>> type(mixed[0]),type(mixed[1]),type(mixed[2])
    (<type 'float'>, <type 'float'>, <type 'numpy.string_'>)
    

    希望有帮助。

    【讨论】:

      【解决方案3】:

      一种可行的方法是检查字符串是否与带有正则表达式的数字匹配,如果匹配则转换为浮点数:

      [float(x) if re.search('[0-9]*\.?[0-9]', x) else x for x in mix]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-25
        • 2011-07-18
        • 2019-10-31
        • 2021-12-28
        • 2013-03-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多