python - 如何将不需要的字符串值转换为 Pandas 中的 NaN
问题描述
我在一项任务中挣扎。我导入了一个不干净的数据框,一些应该只有浮点值的列也有字符串,这些字符串破坏了我的数据并且不允许我执行回归。
如果我有一个混合数据类型的数据框X
和列。"investment_rounds"
我想要类似的东西
np.where(X["investment_rounds"] == np.dtype.str, np.nan, X)
有任何想法吗?
解决方案
他们这里的关键是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
推荐阅读
- python - Plotly-Dash Graph - 显示在形状后面的文本注释
- jsonnet - jsonnet - 从数组中删除空值
- regex - 如何为字符串在正则表达式中包含引号的两个组捕获两种模式(如果存在)
- c# - 使用 DirectLine SDK 和 Xamarin 的高延迟(2-4 秒)机器人响应时间
- python - 在熊猫数据框中移动数据
- python - 在 python 中运行 adb 管道命令
- c# - .NET Int16 限制小于 Oracle 中的 NUMBER(5, 0) 限制
- multithreading - 为什么 Executor.asCoroutineDispatcher 不像 newFixedThreadPoolContext 那样工作?
- angular - D3,Typescript - 'this' 类型的参数不可分配给'BaseType' 类型的参数
- r - 是否有用于合并或替换转换表中向量元素的 R 函数?