如何在Pandas中重新排序多索引列?

时间:2018-10-22 17:45:21

标签: python pandas pivot-table multi-index

df=pd.DataFrame({'Country':["AU","GB","KR","US","GB","US","KR","AU","US"],'Region Manager':['TL','JS','HN','AL','JS','AL','HN','TL','AL'],'Curr_Sales': [453,562,236,636,893,542,125,561,371],'Curr_Revenue':[4530,7668,5975,3568,2349,6776,3046,1111,4852],'Prior_Sales': [235,789,132,220,569,521,131,777,898],'Prior_Revenue':[1530,2668,3975,5668,6349,7776,8046,2111,9852]})

pd.pivot_table(df, values=['Curr_Sales', 'Curr_Revenue','Prior_Sales','Prior_Revenue'],index=['Country', 'Region Manager'],aggfunc=np.sum,margins=True)

enter image description here

伙计们,

我有以下数据框,我想将多索引列重新排序为

['Prior_Sales','Prior_Revenue','Curr_Sales', 'Curr_Revenue']

如何在熊猫中做到这一点?

代码如上所示

提前感谢所有帮助!

2 个答案:

答案 0 :(得分:3)

切片结果数据框

pd.pivot_table(
    df,
    values=['Curr_Sales', 'Curr_Revenue', 'Prior_Sales', 'Prior_Revenue'],
    index=['Country', 'Region Manager'],
    aggfunc='sum',
    margins=True
)[['Prior_Sales', 'Prior_Revenue', 'Curr_Sales', 'Curr_Revenue']]


                        Prior_Sales  Prior_Revenue  Curr_Sales  Curr_Revenue
Country Region Manager                                                      
AU      TL                     1012           3641        1014          5641
GB      JS                     1358           9017        1455         10017
KR      HN                      263          12021         361          9021
US      AL                     1639          23296        1549         15196
All                            4272          47975        4379         39875

答案 1 :(得分:0)

cols = ['Prior_Sales','Prior_Revenue','Curr_Sales', 'Curr_Revenue']

df = df[cols]