Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - return a dataframe after groupby

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

like image 971
Square9627 Avatar asked Jun 23 '16 07:06

Square9627


1 Answers

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
like image 135
jezrael Avatar answered Sep 28 '22 17:09

jezrael