0

I have dataframe in following format:

Date             Category       Value
01-01-2020             A         1
02-01-2020             A         1
01-01-2020             B         2
02-01-2020             B         2

And i need to transform above df in such way that it gives the below output:

Date             Category_A       Category_B
01-01-2020             1                    2
02-01-2020             1                    2

Thanks in advance for the help.

2 Answers2

0

Try:

import pandas as pd

# Supposing that your Data Frame is named df
df_pivot = pd.pivot(df, index='Date', columns='Category', values='Value')

You can find the documentation of Pandas' Pivot here

Thales Marques
  • 333
  • 4
  • 18
0

Here is a full example using pandas pivot_table:

import pandas as pd
data = {'Date':['01-01-2020','02-01-2020','01-01-2020','02-01-2020'],'Category':['A','A','B','B'],'Value':[1,1,2,2]}
df = pd.DataFrame(data)
new_df = pd.pivot_table(df,values='Value',index='Date',columns='Category').rename(columns={'A':'Category_A','B':'Category_B'})
print(new_df)

Output:

Category    Category_A  Category_B
Date                              
01-01-2020           1           2
02-01-2020           1           2

I am using rename because otherwise the column names will be those of the original values for the columns, in this case:

Category    A  B
Date            
01-01-2020  1  2
02-01-2020  1  2
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53