【问题标题】:how to replace a word in a column with NaN in pandas [duplicate]如何在熊猫中用NaN替换列中的单词[重复]
【发布时间】:2021-01-25 13:46:40
【问题描述】:

假设我有一个名为“数量”的列;

Quantity
1
2
3
Plan
3
2

我想将字符串 Plan 替换为 NaN,我该如何在 pandas 中做到这一点?

谢谢

【问题讨论】:

标签: python pandas


【解决方案1】:

如果需要将所有非数值替换为 NaN,并且如果需要将值转换为数值,请使用 to_numeric 和 errors='coerce':

df['Quantity'] = pd.to_numeric(df['Quantity'], errors='coerce')

如果需要只替换字符串Plan:

df['Quantity'] = df['Quantity'].replace('Plan', np.nan)

如果需要转换为数字:

df['Quantity'] = df['Quantity'].replace('Plan', np.nan).astype(float)

【讨论】:

    猜你喜欢
    • 2021-09-08
    • 2019-04-24
    • 2018-08-24
    • 2021-03-22
    • 1970-01-01
    • 2018-03-16
    • 2015-10-12
    • 2019-11-13
    • 2014-07-07
    相关资源
    最近更新 更多