【问题标题】:Pandas dataframe: convert column to number with default value熊猫数据框:将列转换为具有默认值的数字
【发布时间】:2022-01-07 08:36:35
【问题描述】:

我很惊讶我找不到任何关于此的信息:

问:如果转换失败,如何将列的值转换为具有默认值的数字。

我需要所有值都是数字,以便对它们执行算术函数。原始输入数据包含不可转换的值,例如 "","**", "not available", ....

例如

1
2
*
4

应该变成:

1
2
0
4

我尝试过的:

  • to_numberic:不允许设置默认值。 errors=coerce 会将值设置为NaN,之后无法进行算术处理。
  • df[COLUMN].apply (makeNumber)def makeNumber(value): return 0.0 显然对字符串值没有任何作用。

【问题讨论】:

    标签: python pandas type-conversion


    【解决方案1】:

    如果原始使用中没有缺失值:

    df['col'] = pd.to_numeric(df['col'], errors='coerce').fillna(0)
    

    如果需要像评论这样的低调解决方案:

    df['col'] = pd.to_numeric(df['col'], errors='coerce').fillna(0, downcast="infer")
    print (df)
       col
    0    1
    1    2
    2    0
    3    4
    

    如果可能在原始值中缺失并且不需要替换它们:

    print (df)
       col
    0    1
    1    2
    2    *
    3    4
    4  NaN
    
    s = pd.to_numeric(df['col'], errors='coerce')
    
    df['col'] = s.mask(s.isna() & df['col'].notna(), 0)
    print (df)
       col
    0  1.0
    1  2.0
    2  0.0
    3  4.0
    4  NaN
    

    【讨论】:

    • 第二部分非常好+1(可以简化为m = df['col'].notna() ; <change col> ; s.mask(m, 0)
    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 2019-04-19
    • 2017-12-12
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    相关资源
    最近更新 更多