【发布时间】:2020-12-30 00:57:05
【问题描述】:
我在一项任务中挣扎。我导入了一个不干净的数据框,并且一些应该只有浮点值的列也有字符串,这会破坏我的数据并且不允许我执行回归。
如果我有一个包含混合数据类型的数据框 X 和 "investment_rounds" 列。
我想要类似的东西
np.where(X["investment_rounds"] == np.dtype.str, np.nan, X)
有什么想法吗?
【问题讨论】:
我在一项任务中挣扎。我导入了一个不干净的数据框,并且一些应该只有浮点值的列也有字符串,这会破坏我的数据并且不允许我执行回归。
如果我有一个包含混合数据类型的数据框 X 和 "investment_rounds" 列。
我想要类似的东西
np.where(X["investment_rounds"] == np.dtype.str, np.nan, X)
有什么想法吗?
【问题讨论】:
这里的关键是to_numeric的errors='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
【讨论】:
df[['A','B','C']] = df[['A','B','C'].apply(pd.to_numeric, errors='coerce')