Home > Enterprise >  How to manipulate the values in pandas pivot table to be in rows instead?
How to manipulate the values in pandas pivot table to be in rows instead?

Time:09-23

I have a dataframe and I need to change the following dataframe into a Pivot Table of a particular format.

           Date         Name    Transactions           Price
0    2021-09-17         Apple       5                  3.57
1    2021-09-17         Pear        100                6.20
2    2021-09-20         Apple       10                 3.60
3    2021-09-20         Pear        12                 6.10

My codes:

table = pd.pivot_table(data=df,index=['Name'],columns=['Date'],values=['Price','Transactions'])

                       Price                 Transactions    
Date         2021-09-17    2021-09-20   2021-09-17  2021-09-20
Name                                                                                     
Apple          3.57            3.60         5         10
Pear           6.20            6.10        100        12

Desired Output:

Date                                        2021-09-17   2021-09-20
Name                                                                                   
Apple           Transactions                 5              10
                Price                        3.57           3.60
Pear            Transactions                 100            12
                Price                        6.20           6.10

Thank you!

CodePudding user response:

Use DataFrame.stack by first level:

df = table.stack(0)
print (df)
Date                2021-09-17  2021-09-20
Name                                      
Apple Price               3.57         3.6
      Transactions        5.00        10.0
Pear  Price               6.20         6.1
      Transactions      100.00        12.0
  • Related