Skip to main content
 首页 » 编程设计

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

2024年12月31日8Leo_wl

我是 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