【问题标题】:Ignore errors in pandas astype忽略 pandas astype 中的错误
【发布时间】:2018-11-24 07:20:12
【问题描述】:

我有一个数字列,其中可以包含其他不同形式的字符 [0-9]。说:x = pandas.Series(["1","1.2", "*", "1", "**."])。 然后我想使用 x.astype(dtype = float, errors = 'ignore') 将该系列 转换为 数字列。我只是不明白为什么 Pandas 一直给我一个错误,尽管我要求他不要这样做!我的代码有问题吗?

【问题讨论】:

    标签: pandas


    【解决方案1】:

    我想你想改用pd.to_numeric(x, errors='coerce')

    In [73]: x = pd.to_numeric(x, errors='coerce')
    
    In [74]: x
    Out[74]:
    0    1.0
    1    1.2
    2    NaN
    3    1.0
    4    NaN
    dtype: float64
    

    PS 实际上是x.astype(dtype = float, errors = 'ignore') - 按预期工作,它没有给出错误,它只是保留系列,因为它无法转换某些元素:

    In [77]: x.astype(dtype = float, errors = 'ignore')
    Out[77]:
    0      1
    1    1.2
    2      *
    3      1
    4    **.
    dtype: object   # <----- NOTE!!!
    
    In [81]: x.astype(dtype = float, errors = 'ignore').tolist()
    Out[81]: ['1', '1.2', '*', '1', '**.']
    

    【讨论】:

    • 感谢.to_numeric 解决方案。但我不知道是不是因为我的熊猫版本,它一直打印 ValueError: could not convert string to float: '.'**
    • @Neroksi,我使用的是 Pandas 0.23.0。你的 Pandas 版本是什么?
    • 我的熊猫版本是:0.19.2
    猜你喜欢
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2019-07-02
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多