0

I have a df structured in following setting and would like to change it so that the types found in the column type are the the row readers with the original result as the row the new type column, condensing all ids into one row. For example, I would like to change the following table:

id name type result
A Apple 1 X
A Apple 2 X
A Apple 3 X
B Banana 1 Y
B Banana 2 Y
C Cantaloupe 2 Z
C Cantaloupe 3 Z
... ... ... ...

To:

id name 1 2 3
A Apple X X X
B Banana Y Y None
C Cantaloupe None Z Z
... ... ...
aj3409
  • 186
  • 2
  • 14

1 Answers1

0

Try pivot_table with rename_axis:

>>> df.pivot_table('result', ['id', 'name'], 'type', aggfunc=''.join).reset_index().rename_axis(columns=None)
  id        name    1  2    3
0  A       Apple    X  X    X
1  B      Banana    Y  Y  NaN
2  C  Cantaloupe  NaN  Z    Z
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114