gpt4 book ai didi

python - Pandas 获得 groupby 的百分比值

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:55 25 4
gpt4 key购买 nike

<分区>

我有一个我做过的 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 做这个的好方法?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com