Python 将“计数”列添加到 Pandas 中的 groupby 的结果中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48770035/
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
Adding a 'count' column to the result of a groupby in pandas?
提问by Oliver
I think this is a fairly basic question, but I can't seem to find the solution.
我认为这是一个相当基本的问题,但我似乎无法找到解决方案。
I have a pandas dataframe similar to the following:
我有一个类似于以下内容的熊猫数据框:
import pandas as pd
df = pd.DataFrame({'A' : ['x','x','y','z','z'],
'B' : ['p','p','q','r','r']})
df
which creates a table like this:
它创建了一个这样的表:
A B
0 x p
1 x p
2 y q
3 z r
4 z r
I'm trying to create a table that represents the number of distinct values in that dataframe. So my goal is something like this:
我正在尝试创建一个表来表示该数据框中不同值的数量。所以我的目标是这样的:
A B c
0 x p 2
1 y q 1
2 z r 2
I can't find the correct functions to achieve this, though. I've tried:
不过,我找不到正确的功能来实现这一点。我试过了:
df.groupby(['A','B']).agg('count')
This produces a table with 3 rows (as expected) but without a 'count' column. I don't know how to add in that count column. Could someone point me in the right direction?
这将生成一个包含 3 行(如预期)但没有“计数”列的表。我不知道如何添加该计数列。有人能指出我正确的方向吗?
回答by YOBEN_S
You can using size
您可以使用 size
df.groupby(['A','B']).size()
Out[590]:
A B
x p 2
y q 1
z r 2
dtype: int64
For your solution adding one of the columns
对于您的解决方案,添加一列
df.groupby(['A','B']).B.agg('count')
Out[591]:
A B
x p 2
y q 1
z r 2
Name: B, dtype: int64
Update :
更新 :
df.groupby(['A','B']).B.agg('count').to_frame('c').reset_index()
#df.groupby(['A','B']).size().to_frame('c').reset_index()
Out[593]:
A B c
0 x p 2
1 y q 1
2 z r 2