【问题标题】:How to turn unwanted string values into NaNs in pandas如何将不需要的字符串值转换为 Pandas 中的 NaN
【发布时间】:2020-12-30 00:57:05
【问题描述】:

我在一项任务中挣扎。我导入了一个不干净的数据框,并且一些应该只有浮点值的列也有字符串,这会破坏我的数据并且不允许我执行回归。

如果我有一个包含混合数据类型的数据框 X"investment_rounds" 列。

我想要类似的东西

np.where(X["investment_rounds"] == np.dtype.str, np.nan, X) 

有什么想法吗?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这里的关键是to_numericerrors='coerce'参数

    根据Documentation,它将替换任何无法用NaN转换的值

    import pandas as pd
    df = pd.DataFrame({'investment_rounds':['1.0','2.0','bad','data','3.0']})
    df['investment_rounds'] = pd.to_numeric(df['investment_rounds'], errors='coerce')
    

    输出

        investment_rounds
    0   1.0
    1   2.0
    2   NaN
    3   NaN
    4   3.0
    

    【讨论】:

    • 非常感谢,这真的很有帮助。你可以对整个数据框做同样的事情吗?目前,我只是使用了 for 循环。我会投票但还没有声誉:)
    • 如果你有 A、B、C 列并且你想同时转换它们df[['A','B','C']] = df[['A','B','C'].apply(pd.to_numeric, errors='coerce')
    猜你喜欢
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 2015-09-04
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多