Search code examples
pythonpandasgroup-by

Pandas: GroupBy to DataFrame


Referring to this very popular question regarding groupby to dataframe. Unfortunately, I do not think this particular use case is the most useful, here's mine:

Suppose you have what could be a hierarchical dataset in a flattened form, e.g.

     key    val 
0    'a'    2
1    'a'    1
2    'b'    3
3    'b'    4

what I wish to do is convert that dataframe to this structure

    'a'  'b'
0    2    3
1    1    4

I thought this would be as simple as pd.DataFrame(df.groupby('key').groups) but it isn't.

How can I make this transformation?


Solution

  • df.assign(index=df.groupby('key').cumcount()).pivot('index','key','val')
    Out[369]: 
    key    'a'  'b'
    index          
    0        2    3
    1        1    4