I have a dataframe which I have created out of a groupby
operation (see code and output below):
Index=right_asset_df.groupby(['Year','Asset_Type']).agg({'Titre':'count','psqm':'median','Superficie':'median', 'Montant':'median'}).reset_index()
The output is:
Instead of having Asset_Type
as rows, I would like to have it as columns which means that the new output Index
should have one column for each Asset_Type
(Appart and Villa).
Here is an example of the output:
As you can see, the groupby attributes Asset_Type
as one specific column each.
How can I do that in python please? Thanks
CodePudding user response:
Quick way is to use Pivot:
# Pivot table with (index, columns, values)
df = Index.pivot(['Year'], 'Asset_Type',['Titre','psqm','Superficie','Montant']).reset_index()
# Instack multi level in columns
df.columns = ['_'.join(col) for col in df.columns]