Skip to content Skip to sidebar Skip to footer

Best Way To Pivot/Rotate Data Set

I've got the following data frame df = pd.DataFrame({ '1': ['Mon (07/08)','Sales', '2'], '2': ['Mon (07/08)','Stock','3'], '3': ['Mon (07/0

Solution 1:

Take the transpose, then use pivot to reshape. After that, it's just a matter of formatting the axes with rename_axis.

# reshape
df = df.T.pivot(index=0, columns=1, values=2)

# format axes
df = df.rename_axis(None).rename_axis(None, 1)

The resulting output:

            Qty Sales Stock
Mon (07/08)   4     2     3
Tue (08/08)   6     4     5

Solution 2:

You can do this with groupby + sum + unstack:

df.T.groupby([0, 1]).sum().unstack()   # [0, 1] are the column names here

              2            
1           Qty Sales Stock
0                          
Mon (07/08)   4     2     3
Tue (08/08)   6     4     5

Post a Comment for "Best Way To Pivot/Rotate Data Set"