Pandas dataframe groupby to a new dataframe with grouped observation in the same row

Viewed 104

I'm building a df in which observations are grouped two by two as below:

group user amount
ALFA   x    2.3
ALFA   y    1.9
BETA   w    1.8
GAMMA  z    1.3
BETA   s    0.9
GAMMA  q    0.4

I want a new df with user belonging to the same group to be in the same row, as shown below:

user1 user2 amount1 amount2
 x      y     2.3     1.9
 w      s     1.8     0.9
 z      q     1.3     0.4

Values don't need to be sorted in any certain way.

I've tried with df.groupby('group').agg(['min','max']), but this sorts users in alphabetical order instead of corresponding couple user-amount.

Does anybody know how to solve this with pandas?

1 Answers

Group the dataframe on column group then inside a list comprehension using np.hstack horizontally stack the corresponding users and amount and create a new dataframe:

d = pd.DataFrame([
       np.hstack([g['user'], g['amount']]) for _, g in df.groupby('group')],
       columns=['user1', 'user2', 'amount1', 'amount2'])

Result:

  user1 user2  amount1  amount2
0     x     y      2.3      1.9
1     w     s      1.8      0.9
2     z     q      1.3      0.4
Related