重命名Pandas中的MultiIndex列 [英] Rename MultiIndex columns in Pandas

查看:976
本文介绍了重命名Pandas中的MultiIndex列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

df = pd.DataFrame([[1,2,3], [10,20,30], [100,200,300]])
df.columns = pd.MultiIndex.from_tuples((("a", "b"), ("a", "c"), ("d", "f")))
df

返回

     a         d
     b    c    f
0    1    2    3
1   10   20   30
2  100  200  300

df.columns.levels[1]

返回

Index([u'b', u'c', u'f'], dtype='object')

我想将"f"重命名为"e".根据 pandas.MultiIndex.rename 我运行:

I want to rename "f" to "e". According to pandas.MultiIndex.rename I run:

df.columns.rename(["b1", "c1", "f1"], level=1)

但是它引起了

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-110-b171a2b5706c> in <module>()
----> 1 df.columns.rename(["b1", "c1", "f1"], level=1)

C:\Users\USERNAME\AppData\Local\Continuum\Miniconda2\lib\site-packages\pandas\indexes\base.pyc in set_names(self, names, level, inplace)
    994         if level is not None and not is_list_like(level) and is_list_like(
    995                 names):
--> 996             raise TypeError("Names must be a string")
    997 
    998         if not is_list_like(names) and level is None and self.nlevels > 1:

TypeError: Names must be a string

我使用Python 2.7.12 |Continuum Analytics, Inc.| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]'pandas 0.19.1

推荐答案

使用 set_levels :

In [22]:
df.columns.set_levels(['b1','c1','f1'],level=1,inplace=True)
df

Out[22]:
     a         d
    b1   c1   f1
0    1    2    3
1   10   20   30
2  100  200  300

rename 设置名称对于索引,它不会重命名列名称:

rename sets the name for the index, it doesn't rename the column names:

In [26]:
df.columns = df.columns.rename("b1", level=1)
df

Out[26]:
      a         d
b1    b    c    f
0     1    2    3
1    10   20   30
2   100  200  300

这就是为什么您会收到错误消息

This is why you get the error

这篇关于重命名Pandas中的MultiIndex列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆