Skip to main content
 首页 » 编程设计

python之Pandas 获得 groupby 的百分比值

2024年12月31日7findumars

<分区>

我有一个我做过的 pandas groupby

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) 

有没有用 Pandas 做这个的好方法?