Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values of column based on the unique values of another column

I have a data frame of

Column1  Column2
1          20
2          25
3          30
2          40
4          18
1          24

and I want to sum Column2 based on the unique values of Column1. We can find sum based on a specific value such as 1 using this way:

df.loc[df['Column1'] == 1, 'Column2'].sum()

which correctly gives us 44. But how we can do it for all unique values in Column1 such that it produces this one

Column1  Column2
1          44
2          65
3          30
4          18
like image 712
user_01 Avatar asked Nov 28 '22 22:11

user_01


1 Answers

I believe you're looking for groupby. You can find documentation here

df.groupby('Column1')['Column2'].sum()
Column1  Column2
1          44
2          65
3          30
4          18
like image 108
W Stokvis Avatar answered Dec 05 '22 14:12

W Stokvis