【问题标题】:Updating index values column using dictionary使用字典更新索引值列
【发布时间】: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


【解决方案1】:

你把它转换成一个系列:

df.index = df.index.map(dictt).to_series(index=df.index).fillna(df.index.to_series())

【讨论】:

  • 成功了,谢谢。为什么需要将其转换为系列?
猜你喜欢
  • 2017-08-09
  • 2015-05-25
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 2019-01-29
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多