1
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

Hi folks,

I have the following dataframe and I'd like to re-order the muti-index columns as

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

How can I do that in pandas?

The code is shown above

Thanks in advance for all the help!

Boomshakalaka
  • 521
  • 1
  • 6
  • 19

2 Answers2

3

Slice the resulting dataframe

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
piRSquared
  • 285,575
  • 57
  • 475
  • 624
1
cols = ['Prior_Sales','Prior_Revenue','Curr_Sales', 'Curr_Revenue']

df = df[cols]
Pang
  • 9,564
  • 146
  • 81
  • 122
Destiny
  • 141
  • 7