Pandas - 在 groupby 之后返回一个数据帧
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37984736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas - return a dataframe after groupby
提问by Square9627
I have a Pandas df
:
我有一只Pandasdf
:
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:
我想按 column Name
, sum column分组No
,然后返回一个像这样的 2 列数据框:
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
真的很感激任何帮助
回答by jezrael
Add parameter as_index=False
to groupby
:
将参数添加as_index=False
到groupby
:
print (df.groupby(['Name'], as_index=False)['No'].sum())
Name No
0 A 3
1 B 7
Or call reset_index
:
或致电reset_index
:
print (df.groupby(['Name'])['No'].sum().reset_index())
Name No
0 A 3
1 B 7