python - 有条件地替换 Pandas 中的缺失值

标签 python python-3.x python-2.7 pandas dataframe

我是 Python 的新手,学的东西很少。

我有一个用字符串编码的数据集。列表 columns 包含列表中所有列的名称。

columns = ['median', 'p25th', 'p75th']

在这个数据集中,数字以字符串的形式存储。一些列不带数字 & 像这样表示为 UN:

['110000' '75000' '73000' '70000' '65000' 'UN' '62000']

['95000' '55000' '50000' '43000' 'UN' '31500' '48000']

['125000' '90000' '105000' '80000' '75000' '102000' 'UN' '109000']

我需要使用 np.nan 将 UN 替换为 NaN。 我在下面使用了这段代码:

for column in columns:
    recent_grads.loc[column =='UN', column] = np.nan

但我一直收到这个错误:

Traceback (most recent call last):

File "", line 15, in recent_grads.loc[column =='UN', column] = np.nan

File "", line 194, in setitem self._setitem_with_indexer(indexer, value) File "", line 332, in _setitem_with_indexer key, _ = convert_missing_indexer(idx)

File "", line 2049, in convert_missing_indexer raise KeyError("cannot use a single bool to index into setitem") KeyError: 'cannot use a single bool to index into setitem'

你能告诉我哪里错了吗?对不起,如果这听起来太基础了。

最佳答案

您可以尝试使用 Pandas DataFrame replace ,如图所示 here

数据

d = [['median', 'p25th', 'p75th'],
     ['110000','75000','73000','70000','65000','UN','62000'],
     ['95000','55000','50000','43000','UN','31500','48000'],
     ['125000','90000','80000','75000','102000','UN','109000']
    ]
recent_grads = pd.DataFrame(zip(*d[1:]), columns=d[0])
print(recent_grads)

   median  p25th   p75th
0  110000  95000  125000
1   75000  55000   90000
2   73000  50000   80000
3   70000  43000   75000
4   65000     UN  102000
5      UN  31500      UN
6   62000  48000  109000

代码

import numpy as np
columns = ['median', 'p25th', 'p75th']
recent_grads[columns] = recent_grads[columns].replace('UN', np.nan)
print(recent_grads)

   median  p25th   p75th
0  110000  95000  125000
1   75000  55000   90000
2   73000  50000   80000
3   70000  43000   75000
4   65000    NaN  102000
5     NaN  31500     NaN
6   62000  48000  109000

关于python - 有条件地替换 Pandas 中的缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53157088/

相关文章:

python - 传递的类实例何时需要在 python 中导入

python - 从 Google ml-engine (tensorflow) 中的存储桶中读取数据

python - 权重和内核调节器相同吗?

python - 如何在循环外使用循环计数

具有默认值的python模板

python - 如何使用正则表达式拆分列表元素

python - 在 Windows 上通过 Python 脚本运行 Spice 模拟

python - swig:抑制关于函数是 python 关键字的警告

python-3.x - 使用 python pandas 读取 LabVIEW TDMS 文件

python-3.x - Google Cloud Functions-为什么GCF将两个位置参数传递给我的函数?