1

I have a DataFrame as follow:

enter image description here

and now I want group by Username and transform to new DataFrame as:

enter image description here

I using Python 2.7 or 3.6 both OK

1 Answer 1

2

Seems like you want an agg, not a transform...

df = df.groupby('Username')\
         .agg({'Item' : lambda x: x.tolist(), 'Price' : 'sum'})

If you want a comma separated string of words, it would involve an additional str.join:

df = df.groupby('Username')\
      .agg({'Item' : lambda x: ', '.join(x.tolist()), 'Price' : 'sum'})
df

+------------+---------+-----------+
| Username   |   Price | Item      |
|------------+---------+-----------|
| Johne      |    4500 | Food, Tea |
| Mary       |    1000 | Meat      |
| Peter      |    2850 | Food, Egg |
| Ted        |     750 | CK        |
+------------+---------+-----------+
Sign up to request clarification or add additional context in comments.

1 Comment

@PhongNguyen ', '.join(set(x.tolist()))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.