Search code examples
pandasdataframepivot-table

Pivot pandas table into multiple columns


Good day,

I wish to transform my dataFrame into wide format by a grouping variable. Like this:

Group_var |type |value
1         |11    | 111
1         |12    | 111
2         |22    | 222
3         |33    | 333
3         |34    | 334
3         |35    | 335

Into following format:

Group_var |type_1 |value_1 |type_2 |value_2|type_3 |value_3
1         |11    | 111     |12     | 111   |       |
2         |22    | 222     |       |       |       |
3         |33    | 333     |34     | 334   |35     |335

Yeach group_var has differing amount of values and types making pivoting a problem. Any ideas how to do this?


Solution

  • What about using pivot_table with an aggregate function of list then explode it and concatenate type and value dataframe values:

    df = df.pivot_table(values=['type', 'value'], index='Group_var', aggfunc=list)
    df = pd.concat([df[c].apply(pd.Series).add_prefix(c + "_") for c in df], axis=1).reset_index()
    
    print(df)
    

    Output:

       Group_var  type_0  type_1  type_2  value_0  value_1  value_2
    0          1    11.0    12.0     NaN    111.0    111.0      NaN
    1          2    22.0     NaN     NaN    222.0      NaN      NaN
    2          3    33.0    34.0    35.0    333.0    334.0    335.0