How to swap the column header in pandas pivot table?

江枫思渺然 提交于 2020-05-09 05:37:08

问题


Following up from this question

I got a datframe after pivoting like this .

                      AVG GrossProfit      AVG PMV      Loss%         Sales      
ParentAuction       Copart   IAA        Copart   IAA   Copart IAA    Copart   IAA 
Make                                                                        
Acura               112.99  NaN         -15.53   NaN   36.46  NaN      96.0  NaN

How to change the column levels to this format of columns ?

ParentAuction                 Copart                                    IAA          
                 AVG GrossProfit AVG PMV  Loss%  Sales  AVG GrossProfit AVG PMV   Loss%   Sales  
Make                                                                          
Acura                  112.99  -15.53  36.46   96.0             NaN     NaN       NaN      NaN

回答1:


Use swaplevel with sort_index for sorting MultiIndex:

df = df.swaplevel(0,1, axis=1).sort_index(axis=1)
print (df)
ParentAuction           Copart                                  IAA          \
               AVG GrossProfit AVG PMV  Loss% Sales AVG GrossProfit AVG PMV   
Make                                                                          
Acura                   112.99  -15.53  36.46  96.0             NaN     NaN   

ParentAuction               
               Loss% Sales  
Make                        
Acura            NaN   NaN  


来源:https://stackoverflow.com/questions/46168316/how-to-swap-the-column-header-in-pandas-pivot-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!