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
Run Code Online (Sandbox Code Playgroud)
回报
a d
b c f
0 1 2 3
1 10 20 30
2 100 200 300
Run Code Online (Sandbox Code Playgroud)
和
df.columns.levels[1]
Run Code Online (Sandbox Code Playgroud)
回报
Index([u'b', u'c', u'f'], dtype='object')
Run Code Online (Sandbox Code Playgroud)
我想重命名"f"为"e".据pandas.MultiIndex.rename我说:
df.columns.rename(["b1", "c1", "f1"], level=1)
Run Code Online (Sandbox Code Playgroud)
但它提出了
---------------------------------------------------------------------------
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 …Run Code Online (Sandbox Code Playgroud) 我有一个数据框,有多grouped索引列,如下所示:
import pandas as pd
codes = ["one","two","three"];
colours = ["black", "white"];
textures = ["soft", "hard"];
N= 100 # length of the dataframe
df = pd.DataFrame({ 'id' : range(1,N+1),
'weeks_elapsed' : [random.choice(range(1,25)) for i in range(1,N+1)],
'code' : [random.choice(codes) for i in range(1,N+1)],
'colour': [random.choice(colours) for i in range(1,N+1)],
'texture': [random.choice(textures) for i in range(1,N+1)],
'size': [random.randint(1,100) for i in range(1,N+1)],
'scaled_size': [random.randint(100,1000) for i in range(1,N+1)]
}, columns= ['id', 'weeks_elapsed', 'code','colour', 'texture', 'size', 'scaled_size'])
grouped = df.groupby(['code', …Run Code Online (Sandbox Code Playgroud)