Reputation: 161
I have a python pandas data frame like this
col1 col2 col3
s1 a 2
s1 b 1
s1 c 3
s2 d 2
s2 e 5
s2 f 1
s3 a 2
I want to reshape it like this
col1 col2_appended col3_sum
s1 a,b,c 6
s2 d,e,f 8
s3 a 2
First column has distinct values from col1, the second column has values of col2 concatenated with commas and the 3rd column has sum of col3.
Upvotes: 1
Views: 61
Reputation: 59274
Use
df.groupby('col1', as_index=False).agg({'col2': ','.join, 'col3': sum})
col1 col2 col3
0 s1 a,b,c 6
1 s2 d,e,f 8
2 s3 a 2
Upvotes: 4