在“ pandas 人" groupby的结果中添加“计数"列? [英] Adding a 'count' column to the result of a groupby in pandas?
问题描述
我认为这是一个非常基本的问题,但是我似乎找不到解决方法.
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
创建一个像这样的表:
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')
这将产生一个表,该表具有3行(按预期),但没有'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?
推荐答案
您可以使用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
更新:
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
这篇关于在“ pandas 人" groupby的结果中添加“计数"列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!