【问题标题】:convert pandas to_numeric with 'ignore' errors failing to convert strings将 pandas to_numeric 转换为“忽略”错误无法转换字符串
【发布时间】:2020-04-13 18:33:13
【问题描述】:

我想使用带有错误的pd.to_numeric 将系列值转换为数字:'ignore',因为我还需要保留一些字符串。这应该非常简单,但由于某种原因 pd.to_numeric 无法转换为数值。我正在使用熊猫版本 1.0.3。

我本来希望将字符串保持原样,将 '1' 转换为 int 并将 '1.2' 转换为 float,但似乎并非如此。难道我做错了什么?是bug吗?

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    它的工作方式不同,请查看to_numeric

    如果“忽略”,则无效解析将返回输入。

    换句话说,如果错误它返回未更改的数据。

    关闭,您需要使用 errors='coerce' 进行转换,然后替换缺失值(所有数字都是浮点数,因为至少有一个 float 并且因为 NaN 是浮点数):

    s = pd.Series(['apple','1','1.2',2])
    
    print (pd.to_numeric(s, errors='coerce').fillna(s))
    0    apple
    1        1
    2      1.2
    3        2
    dtype: object
    

    print (pd.to_numeric(s, errors='coerce').fillna(s).map(type))
    0      <class 'str'>
    1    <class 'float'>
    2    <class 'float'>
    3    <class 'float'>
    dtype: object
    

    【讨论】:

    • 谢谢,是的,我误解了文档
    猜你喜欢
    • 2018-01-23
    • 2019-10-21
    • 2022-11-19
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多