I have a Pandas df
:
Name No
A 1
A 2
B 2
B 2
B 3
I want to group by column Name
, sum column No
and then return a 2-column dataframe like this:
Name No
A 3
B 7
I tried:
df.groupby(['Name'])['No'].sum()
but it does not return my desire dataframe. I can't add the result to a dataframe as a column.
Really appreciate any help
Add parameter as_index=False
to groupby
:
print (df.groupby(['Name'], as_index=False)['No'].sum())
Name No
0 A 3
1 B 7
Or call reset_index
:
print (df.groupby(['Name'])['No'].sum().reset_index())
Name No
0 A 3
1 B 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With