Tuesday, April 27, 2021

How to Pivot a Pandas dataframe

How to Pivot a Pandas dataframe
In [10]:
import pandas as pd

df = pd.DataFrame({'Account':['Internal Revenue', 'Assets', 'External Rev', 'Rent'],
        'Amount':[89989, 299499, 20992, 3200],
        'Year_Month':['2021_01', '2021_02', '2021_03', '2021_04']})
In [11]:
df.head()
Out[11]:
Account Amount Year_Month
0 Internal Revenue 89989 2021_01
1 Assets 299499 2021_02
2 External Rev 20992 2021_03
3 Rent 3200 2021_04
In [12]:
df=df.pivot_table('Amount', ['Account'], 'Year_Month')
df=df.fillna(0)
df.head()
Out[12]:
Year_Month 2021_01 2021_02 2021_03 2021_04
Account
Assets 0.0 299499.0 0.0 0.0
External Rev 0.0 0.0 20992.0 0.0
Internal Revenue 89989.0 0.0 0.0 0.0
Rent 0.0 0.0 0.0 3200.0
In [ ]:
 

No comments:

Post a Comment