相关疑难解决方法(0)

在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
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)

pandas

30
推荐指数
6
解决办法
3万
查看次数

具有多索引列的Pandas数据框 - 合并级别

我有一个数据框,有多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)

python multi-index pandas

29
推荐指数
4
解决办法
2万
查看次数

标签 统计

pandas ×2

multi-index ×1

python ×1