Boomshakalaka
Boomshakalaka

Reputation: 521

How to reorder multi-index columns in Pandas?

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!

Upvotes: 1

Views: 1721

Answers (2)

Destiny
Destiny

Reputation: 141

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

df = df[cols]

Upvotes: 1

piRSquared
piRSquared

Reputation: 294218

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

Upvotes: 3

Related Questions