1

So I have multiple (in my case exactly 2, but this may vary) observations per 'group' and want to convert this info to a single observation as shown below. Maybe I miss something obvious here but how to convert

    type    value
group       
A   1   0.3
A   2   0.1
B   3   0.2
B   1   0.1

into

    type1   value1  type2   value2
group               
A   1   0.3 2   0.1
B   3   0.2 1   0.1
pfuhlert
  • 533
  • 4
  • 16
  • Some search terms to help you: your data is in "long format" and you are looking to put it into "wide format". This operation is variously known as "pivoting", "reshaping", "casting", or "unstacking". – shadowtalker May 19 '20 at 14:22

1 Answers1

0

You can set a new index level and unstack:

new_df = (df.set_index(df.groupby(level=0).cumcount()+1, append=True)
   .unstack(level=-1)
   .sort_index(level=(1,0), axis=1)
)

new_df.columns = [f'{x[0]}{x[1]}' for x in new_df.columns]

Output:

       type1  value1  type2  value2
group                              
A          1     0.3      2     0.1
B          3     0.2      1     0.1
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74