首页 > 解决方案 > 如何将不需要的字符串值转换为 Pandas 中的 NaN

问题描述

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

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

我想要类似的东西

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

有任何想法吗?

标签: pythonpandas

解决方案


他们这里的关键是errors='coerce'参数to_numeric

根据文档,它将替换任何无法转换的值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

推荐阅读