python - Pandas 根据字典替换行的索引

标签 python pandas dictionary dataframe

<分区>

我有一个名为 df 的 Pandas 数据框:

             1   2   3   4   5   6   7   8   9   10
dog   jumps   1   1   1   1   1   1   0   1   1   1
      fox     1   1   1   1   1   1   0   0   1   1
      the     1   1   1   1   1   1   1   0   1   1
      dog     1   1   1   1   1   1   0   0   1   1
      over    1   1   1   1   1   1   0   0   1   1
fox   jumps   1   1   1   1   1   1   0   1   1   1
      fox     1   1   1   1   1   1   0   0   1   1
      the     1   1   1   1   1   1   1   0   1   1
      dog     1   1   1   1   1   1   0   0   1   1
      over    1   1   1   1   1   1   0   0   1   1
jumps jumps   1   1   1   1   1   1   0   0   1   0
      fox     1   1   1   1   1   1   1   0   1   0
      the     1   0   1   1   1   1   0   0   1   0
      dog     1   1   1   1   1   1   1   0   1   0
      over    1   0   1   1   1   0   0   1   1   0
over  jumps   1   1   0   1   0   1   1   0   1   0
      fox     1   1   1   1   1   1   0   0   1   0
      the     1   0   1   1   1   0   0   1   1   0
      dog     1   1   1   1   1   1   0   0   1   0
      over    1   1   1   1   1   1   0   0   1   0
the   jumps   1   1   0   1   1   1   0   0   1   0
      fox     1   1   1   1   1   1   0   1   1   0
      the     1   1   1   1   1   1   0   0   1   0
      dog     1   1   1   1   1   1   0   1   1   0
      over    1   1   0   1   0   1   1   0   1   0

我有以下字典:

dic = {'dog': 1, 'fox': 1, 'the': 2, 'over': 2, 'jumps': 0}

我想用 dic 中的相应值替换索引的值。

我尝试了以下方法:

df.index.levels[0][0] = 'integer value'

但这不起作用,它给了我错误:

TypeError: Index does not support mutable operations

还有 pandas rename function也不行

关于如何以最有效和干净的方式执行此操作的任何想法。任何建议将不胜感激。

最佳答案

我认为 rename 仍然有效

df.rename(index=dic)
Out[1311]: 
     1  2  3  4  5  6  7  8  9  10                               
1 0  1  1  1  1  1  1  0  1  1   1
  1  1  1  1  1  1  1  0  0  1   1
  2  1  1  1  1  1  1  1  0  1   1
  1  1  1  1  1  1  1  0  0  1   1
  2  1  1  1  1  1  1  0  0  1   1
  0  1  1  1  1  1  1  0  1  1   1
  1  1  1  1  1  1  1  0  0  1   1
  2  1  1  1  1  1  1  1  0  1   1
  1  1  1  1  1  1  1  0  0  1   1
  2  1  1  1  1  1  1  0  0  1   1

关于python - Pandas 根据字典替换行的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48798687/

相关文章:

python - 我需要编写一个正则表达式来识别所有以逗号分隔或不分隔的数字,不包括 4 位数字

python - Pandas Python 上的 Group by 和 where 查询

python - Pandas DataFrame 过滤 ||仅保留列的连续元素

c# - 在 C# 中,如何从字典中获取键列表?

c++ - 将 map 与自定义对象一起使用时出错?可能是语法问题

python - 计算 Pandas 系列中下划线后的值

用于日期操作的 Python 模块

python - 有效地识别字符串的一部分是否在列表/字典键中?

python - Pandas drop_duplicates 方法不适用于包含列表的数据框

键不存在时对象的 C++ 映射删除