Home > other >  dataframe pivot based on 3 columns
dataframe pivot based on 3 columns

Time:10-06

I have a data frame like shown below

customer organization currency volume revenue Duration
Peter XYZ Ltd CNY, INR 20 3,000 01-Oct-2022
John abc Ltd INR 7 184 01-Oct-2022
Mary aaa Ltd USD 3 43 03-Oct-2022
John bbb Ltd THB 17 2,300 04-Oct-2022
Dany ccc Ltd CNY, INR , KRW 45 15,100 04-Oct-2022

If I pivot as shown below

df = pd.pivot_table(df, values=['runs', 'volume','revenue'],
                        index=['customer', 'organization', 'currency'],
                        columns=['Duration'],
                        aggfunc=sum,
                        fill_value=0
                  )

level = 0 becomes volume for all Duration (level 1) revenue for all Duration duration for all Duration.

I would like to pivot by Duration as level 0 and volume, revenue as level 2.

How to achieve it?

Current output: enter image description here

I would like to have date as level 0 and volume, revenue and runs under it.

CodePudding user response:

You can use swaplevel like below in your current pivot code; try this;

df1 = df.pivot_table(index=['customer', 'organization', 'currency'],
                        columns=['Duration'],
                        aggfunc=sum,
                        fill_value=0).swaplevel(0,1, axis=1).sort_index(axis=1)

Hope this Helps...

  • Related