How to iterate and flatten each column in one groupby value

Viewed 76

I want to firstly group different rows, if their first item in the row is the same, then flatten each columns in one group into a list.

My initial dataframe:

enter image description here

And my target:

enter image description here

The problem is that I cannot use simply df.groupby('key').apply(list) cause it will flatten columns val1 and val2 together`

Is there any way to do this?

1 Answers

Use agg instead of apply:

df.groupby('key').agg(list)

Output:

    key       val1       val2
0  key1  [1, 2, 5]  [2, 3, 6]
Related