Opposite of melt in python pandas
there are a few ways;
using .pivot
:
>>> origin.pivot(index='label', columns='type')['value']type a b clabel x 1 2 3y 4 5 6z 7 8 9[3 rows x 3 columns]
using pivot_table
:
>>> origin.pivot_table(values='value', index='label', columns='type') value type a b clabel x 1 2 3y 4 5 6z 7 8 9[3 rows x 3 columns]
or .groupby
followed by .unstack
:
>>> origin.groupby(['label', 'type'])['value'].aggregate('mean').unstack()type a b clabel x 1 2 3y 4 5 6z 7 8 9[3 rows x 3 columns]
DataFrame.set_index
+ DataFrame.unstack
df.set_index(['label','type'])['value'].unstack()type a b clabel x 1 2 3y 4 5 6z 7 8 9
simplifying the passing of pivot arguments
df.pivot(*df)type a b clabel x 1 2 3y 4 5 6z 7 8 9
[*df]#['label', 'type', 'value']
For expected output we need DataFrame.reset_index
and DataFrame.rename_axis
df.pivot(*df).rename_axis(columns = None).reset_index() label a b c0 x 1 2 31 y 4 5 62 z 7 8 9
if there are duplicates in a,b
columns we could lose information so we need GroupBy.cumcount
print(df) label type value0 x a 11 x b 22 x c 33 y a 44 y b 55 y c 66 z a 77 z b 88 z c 90 x a 11 x b 22 x c 33 y a 44 y b 55 y c 66 z a 77 z b 88 z c 9
df.pivot_table(index = ['label', df.groupby(['label','type']).cumcount()], columns = 'type', values = 'value')type a b clabel x 0 1 2 3 1 1 2 3y 0 4 5 6 1 4 5 6z 0 7 8 9 1 7 8 9
Or:
(df.assign(type_2 = df.groupby(['label','type']).cumcount()) .set_index(['label','type','type_2'])['value'] .unstack('type'))