Pandas得到groupby的百分比值

2024-05-13 10:30:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个熊猫团员

grouped = df.groupby(['name','type'])['count'].count().reset_index()

看起来像这样:

name  type    count
x     a       32
x     b       1111
x     c       4214

我需要做的是得到这个并生成百分比,所以我会得到这样的结果(我意识到百分比是不正确的):

name  type  count
x     a     1%
x     b     49%
x     c     50%

我可以想出一些可能有意义的伪代码,但我还没有得到任何实际工作。。。你知道吗

像这样的

def getPercentage(df):
    for name in df: 
        total = 0
        where df['name'] = name:
            total = total + df['count'] 
            type_percent = (df['type'] / total) * 100
            return type_percent

df.apply(getPercentage)

有没有一个好的方法来处理熊猫呢?你知道吗


Tags: namedfindextypecounttotal百分比reset
3条回答

任何序列都可以通过传入参数“normalize=False”进行规范化,如下所示(这比按计数进行偏差更简单):

Series.value_counts(normalize=True, sort=True, ascending=False) 因此,它将类似于(这是一个系列,而不是一个数据帧):

df['type'].value_counts(normalize=True) * 100

或者,如果您使用groupby,您可以简单地执行以下操作:

total = grouped['count'].sum()
grouped['count'] = grouped['count']/total * 100

使用crosstab+normalize

pd.crosstab(df.name,df.type,normalize='index').stack().reset_index()

尝试:

df.loc[:,'grouped'] = df.groupby(['name','type'])['count'].count() / df.groupby(['name','type'])['count'].sum()

相关问题 更多 >