如何将Pandas Dataframe MultiIndex行旋转为MultiIndex列?

问题描述 投票:2回答:1

我想知道是否有人可以帮我解决这个问题。

如果我有一个简单的数据帧:

  one  two three  four
0   A    1     a    1
1   A    2     b    2
2   B    1     c    3
3   B    2     d    4
4   C    1     e    5
5   C    2     f    6

我可以通过发出以下命令轻松地在行上创建多索引:

a.set_index(['one', 'two'])

         three   four
one two      
A    1     a       1
     2     b       2
B    1     c       3
     2     d       4
C    1     e       5
     2     f       6

是否有类似的简单方法在列上创建多索引?

这是达到这一点的代码。

import numpy as np
import pandas as pd
df=[['A','1','a','1'],['A','2','b','2'],['B','1','c','3'],
    ['B','2','d','4'],['C','1','e','5'],['C','2','f','6']]
df=pd.DataFrame(df)
df.columns=['one','two','three','four']
df.set_index(['one','two'])

我想最终得到:

       A            B           C
two    three four   three four  three four
1       a      1     c      3     e    5
2       b      2     d      4     f    6

谢谢。

python python-3.x pandas
1个回答
1
投票

这可以使用unstack + swaplevel + sort_index完成 -

df

        three four
one two           
A   1       a    1
    2       b    2
B   1       c    3
    2       d    4
C   1       e    5
    2       f    6

df = df.unstack(0)
df.columns = df.columns.swaplevel()

df.sort_index(axis=1)

one    A          B          C      
    four three four three four three
two                                 
1      1     a    3     c    5     e
2      2     b    4     d    6     f
© www.soinside.com 2019 - 2024. All rights reserved.