Kenan
Kenan

Reputation: 14094

Pandas pivot on one column with aggregation

Input dataframe

                                 Breakdown 12/31/2019 12/31/2018 12/31/2017 12/31/2016
0                             Total Assets    2926082    1997917     829758     369359
1  Total Liabilities Net Minority Interest    1771226     681684     213528      26454
2     Total Equity Gross Minority Interest    1154856    1316233     616230     342905
3                     Total Capitalization    2307673    1131101     560000     271539
4                      Common Stock Equity     813999     572080     475000     271539

I want to pivot on the breakdown column and have the remaining date columns become the index. I have tried pivot and pivot_table but keep getting aggregation errors

I finally figure out a long way by

df = df.T
df.columns = df.loc['Breakdown']
df = df.drop('Breakdown', axis=0)

But i think there should be a better approach to this problem

Expected output

Breakdown   Total Assets  Total Liabilities Net Minority Interest  Total Equity Gross Minority Interest  Total Capitalization  Common Stock Equity
12/31/2019       2926082                                  1771226                               1154856               2307673               813999
12/31/2018       1997917                                   681684                               1316233               1131101               572080
12/31/2017        829758                                   213528                                616230                560000               475000
12/31/2016        369359                                    26454                                342905                271539               271539

Upvotes: 0

Views: 45

Answers (2)

BENY
BENY

Reputation: 323226

Do it T

df=df.set_index('Breakdown').T

Upvotes: 2

sammywemmy
sammywemmy

Reputation: 28644

A combination of stack and unstack should help here: set Breakdown as the index, stack the remaining columns, then unstack the Breakdown column to get your output :

df.set_index("Breakdown").stack().unstack(0)

Upvotes: 1

Related Questions