【发布时间】:2021-12-01 23:22:47
【问题描述】:
所以我已经阅读了一些有用的帖子,但我仍然无法弄清楚我做错了什么。我有一本字典,我想用它来更新由一堆不同名称组成的数据框的索引。
如果数据框的索引和字典中存在名称,则我将其替换为新名称。如果它不存在,那么我不会用 nan 替换,而是保留当前名称。
这是我迄今为止尝试过的:
第一次尝试:
df.index = df.index.map(dictt).fillna(df.index)
错误:
'value' must be scalar, passed: Index
第二次尝试
df.index = df.index.replace(dictt)
错误:
'Index object has no attribute 'replace'
第三次尝试
x = dictt.keys()
for name in df.index:
if name in x:
df.index[name].map(dictt)
错误:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
【问题讨论】:
-
第一个错误是因为fillna需要一个单一的值?你正在传递一个索引?
标签: python dataframe dictionary replace