Skip to main content
 首页 » 编程设计

python之如何将 Pandas Dataframe MultiIndex 行旋转到 MultiIndex 列中

2025年01月19日7luoye11

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

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

  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 

谢谢。

请您参考如下方法:

这可以使用 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