Michael
Michael

Reputation: 153

pandas groupby to new columns

I have the following table

Group Value Name
1 1.1 AAAA
1 1.2 BBBB
2 1.4 CCCC
2 1.6 DDDD
3 0.4 EEEE
3 0.3 FFFF

I'd like to transform the table to the following by grouping by the group ID:

Group Value_1 Name_1 Value_2 Name_2
1 1.1 AAAA 1.2 BBBB
2 1.4 CCCC 1.6 DDDDD
3 0.4 EEEE 0.3 FFFF

For now a solution, assuming there are only two rows per group is fine, but if possible I'd like to see a solution with more than two rows.

Upvotes: 1

Views: 46

Answers (1)

mcsoini
mcsoini

Reputation: 6642

Adding a counter for each group and then unstack:

df_wide = (df.assign(count=(df.groupby("Group").cumcount() + 1).astype(str))
             .set_index(["Group", "count"])
             .unstack("count")
             .sort_index(axis=1, level=1))
df_wide.columns = df_wide.columns.map('{0[0]}_{0[1]}'.format)

df_wide

      Name_1  Value_1 Name_2  Value_2
Group                                
1       AAAA      1.1   BBBB      1.2
2       CCCC      1.4   DDDD      1.6
3       EEEE      0.4   FFFF      0.3

Upvotes: 2

Related Questions