【问题标题】:Forced conversion of non-numeric numpy arrays with NAN replacement使用 NAN 替换强制转换非数字 numpy 数组
【发布时间】:2013-04-19 20:42:51
【问题描述】:

考虑数组

x = np.array(['1', '2', 'a'])

绑定到浮点数组会引发异常

x.astype(np.float)
ValueError: could not convert string to float: a

numpy 是否提供任何有效的方法将其强制转换为数字数组,用 NAN 之类的东西替换非数字值?

或者,是否有一个等效于np.isnan 的高效 numpy 函数,但它也可以测试字母等非数字元素?

【问题讨论】:

    标签: python numpy type-conversion nan coercion


    【解决方案1】:

    您可以使用np.genfromtxt 将字符串数组转换为浮点数组(使用 NaN):

    In [83]: np.set_printoptions(precision=3, suppress=True)
    
    In [84]: np.genfromtxt(np.array(['1','2','3.14','1e-3','b','nan','inf','-inf']))
    Out[84]: array([ 1.   ,  2.   ,  3.14 ,  0.001,    nan,    nan,    inf,   -inf])
    

    这是一种识别“数字”字符串的方法:

    In [34]: x
    Out[34]: 
    array(['1', '2', 'a'], 
          dtype='|S1')
    
    In [35]: x.astype('unicode')
    Out[35]: 
    array([u'1', u'2', u'a'], 
          dtype='<U1')
    
    In [36]: np.char.isnumeric(x.astype('unicode'))
    Out[36]: array([ True,  True, False], dtype=bool)
    

    请注意,“数字”是指仅包含数字字符的 Unicode,即具有 Unicode 数值属性的字符。它包含小数点。所以u'1.3' 不被视为“数字”。

    【讨论】:

    • 这个答案可能需要修改 python3 - 你会得到TypeError: Can't convert 'bytes' object to str implicitly
    • @cᴏʟᴅsᴘᴇᴇᴅ:感谢您的提醒。用astype('bytes') 修复。
    • 没问题。一如既往的好答案,感谢知识分享!
    • 现在无需转换为字节即可工作
    • 如果列表同时包含字符串和数字,可以使用np.genfromtxt(np.array(x, dtype=str))
    【解决方案2】:

    如果你碰巧也在使用 pandas,你可以使用 pd.to_numeric() 方法:

    In [1]: import numpy as np
    
    In [2]: import pandas as pd
    
    In [3]: x = np.array(['1', '2', 'a'])
    
    In [4]: pd.to_numeric(x, errors='coerce')
    Out[4]: array([  1.,   2.,  nan])
    

    【讨论】:

      猜你喜欢
      • 2011-10-05
      • 2012-03-21
      • 2019-05-10
      • 2015-03-02
      • 1970-01-01
      • 2012-06-13
      • 2013-09-12
      • 2015-05-05
      • 1970-01-01
      相关资源
      最近更新 更多