Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group together rows of Pandas Dataframe with same values in first 2 columns by summing values in the 3rd column?

I have a dataframe of the form:

enter image description here

For same values of col1 and col2 (for example, A B), I want to add all values in the col3 of the dataframe such that only one row of that form (A B) remains and all values in col3 correspond to those are added.

The result would look like:

enter image description here

I tried:

df.groupby(['col1', 'col2'], axis=0, as_index=True).sum()

but it gave me:

enter image description here

which is not exactly what I am looking for. Please help and advise. Thanks in advance.

like image 739
PyAndy Avatar asked Sep 13 '25 03:09

PyAndy


1 Answers

You just need to do this, False instead of True:

df.groupby(['col1', 'col2'], axis=0, as_index=False).sum()
like image 102
NYC Coder Avatar answered Sep 15 '25 17:09

NYC Coder