python - 如何将数值与 nan 值分开?

标签 python pandas

我有很多缺失数据的 Pandas 数据框。如果我去

d = dfs['REV_PIZ'].isna()

输出是 bool 值。

0        True
1        True
2        True
3        True
4        True
5        True
6        True
7        True

我真正想要的是让 d 只包含数值,这将使我能够在此专栏上进一步进行数学运算。

最佳答案

不清楚是否有非数值,所以2种可能的解决方案:


如果所有值都是数字,则可以使用 boolean indexingisna :

d = dfs[dfs['REV_PIZ'].notna()]

dropna按列 REV_PIZ:

d = dfs.dropna(subset=['REV_PIZ'])

示例:

dfs = pd.DataFrame({'REV_PIZ':[1,2,np.nan]})
d = dfs.dropna(subset=['REV_PIZ'])
print (d)
   REV_PIZ
0      1.0
1      2.0

如果数字与非数字混合添加 to_numeric使用 errors='coerce' 将非数字转换为 NaN:

dfs = pd.DataFrame({'REV_PIZ':[1,2,np.nan,'a']})
dfs['REV_PIZ'] = pd.to_numeric(dfs['REV_PIZ'], errors='coerce')
d = dfs.dropna(subset=['REV_PIZ'])
print (d)
   REV_PIZ
0      1.0
1      2.0

关于python - 如何将数值与 nan 值分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49595125/

相关文章:

python - selenium.common.exceptions.WebDriverException : Message: 'chromedriver' executable needs to be in PATH

python - 如何在 Python matplotlib 中的曲线下填充彩虹色

python - 类似的字符串,并希望在 python 中使用 RegEx、Pandas 创建 3 个单独的数据帧

python Pandas : flag duplicate rows

python - 在 pandas Series 中设置值很慢,为什么?

python - 合并属于时间序列一部分的多个数据文件(具有多个列)

python - 在 python 上创建登录页面

python - docker项目中mysql配置的不同主机值产生不同的错误

Python Pandas df,将货币金额中的 $、M 和 K 替换为 int 的最佳方法

python - 从 datetime64[ns, UTC], Python 中提取年月日