Home > Software engineering >  Pandas move grouped column items as columns
Pandas move grouped column items as columns

Time:06-02

Lets say I have the following dataframe -

import pandas as pd
df = pd.DataFrame({'c1': ['a', 'a', 'a', 'b', 'b', 'c'], 'c2': ['x', 'y', 'z', 'y', 'x', 'x'], 'c3': [1, 2, 3, 4, 5, 2]})
    c1  c2  c3
0   a   x   1
1   a   y   2
2   a   z   3
3   b   y   4
4   b   x   5
5   c   x   2

by df.groupby(['c1', 'c2']).mean() it produces

enter image description here

which is fine, but would require in the form as the image.

enter image description here

CodePudding user response:

IIUC , you just want to pivot your df:

df = df.pivot(index=['c1'],columns = 'c2')

output:

>>
     c3          
c2    x    y    z
c1               
a   1.0  2.0  3.0
b   5.0  4.0  NaN
c   2.0  NaN  NaN
  • Related