python - Pandas 重命名: change values of index for a specific column only

标签 python pandas indexing

我有以下 pandas 数据框:

                   Cost
Year  Month  ID  
2016  1      10    40
      2      11    50
2017  4      1     60

年份月份ID组成索引。我想将 Month 中的值设置为等效名称(例如 1 = Jan,2 = Feb)。我想出了以下代码:

df.rename(index={i: calendar.month_abbr[i] for i in range(1, 13)}, inplace=True)

但是,这会更改索引中每一列中的值:

                   Cost
Year  Month  ID  
2016  Jan    10    40
      Feb    11    50
2017  Apr    Jan   60    # Jan here is incorrect

我显然只想更改“月份”列中的值。我该如何解决这个问题?

最佳答案

使用set_levels

m = {1: 'Jan', 2: 'Feb', 4: 'Mar'}
df.index.set_levels(
    df.index.levels[1].to_series().map(m).values,
    1, inplace=True)

print(df)

               Cost
Year Month ID      
2016 Jan   10    40
     Feb   11    50
2017 Mar   1     60

关于python - Pandas 重命名: change values of index for a specific column only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43357056/

相关文章:

python - 在一个 Beautiful Soup 脚本中抓取多个页面——得到相同的结果

python - 如何解决TypeError : list indices must be integers, not list?

sql - SQL Server如何将索引从一个表复制到另一个表

Excel IF(ISNUMBER(SEARCH 忽略某些字符

python - LDA生成主题的自动标注

Python - 仅使用循环删除空格

python - 如何删除列值为 NaN 的行的百分比

python - 如何计算具有 NaN 值的 pandas DataFrame 的平均值

sql - 外键可以提高查询性能吗?

javascript - 无法在 Firefox 上建立 Websocket 安全连接