Pandas - dataframe groupby - how to get sum of multiple columns
By using apply
df.groupby(['col1', 'col2'])["col3", "col4"].apply(lambda x : x.astype(int).sum())
Out[1257]:
col3 col4
col1 col2
a c 2 4
d 1 2
b d 1 2
e 2 4
If you want to agg
df.groupby(['col1', 'col2']).agg({'col3':'sum','col4':'sum'})
Another generic solution is
df.groupby(['col1','col2']).agg({'col3':'sum','col4':'sum'}).reset_index()
This will give you the required output.
UPDATED (June 2020): Introduced in Pandas 0.25.0, Pandas has added new groupby behavior “named aggregation” and tuples, for naming the output columns when applying multiple aggregation functions to specific columns.
df.groupby(['col1','col2']).agg(
sum_col3 = ('col3','sum'),
sum_col4 = ('col4','sum'),
).reset_index()
Also, you can name new columns, e.g. I've used 'sum_col3' and 'sum_col4', but you can use any name you want.
Refer to Link for detailed description.