有条件地替换Pandas的缺失值

2024-04-26 00:21:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不太熟悉,我学到的东西不多。在

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

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公司. 我使用以下代码:

^{pr2}$

但我一直收到这样的错误:

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'

我能告诉你哪里错了吗?抱歉,如果这听起来太基本了。在


Tags: 数据字符串in列表withnplinecolumn
1条回答
网友
1楼 · 发布于 2024-04-26 00:21:42

您可以尝试使用Pandas数据帧^{},如图所示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

代码

^{pr2}$

相关问题 更多 >