gpt4 book ai didi

python - 如何在 Python 中计算 groupby 中的计数和百分比

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:39 25 4
gpt4 key购买 nike

分组后输出结果如下

Publisher.groupby('Category')['Title'].count()
Category
Coding 5
Hacking 7
Java 1
JavaScript 5
LEGO 43
Linux 7
Networking 5
Others 123
Python 8
R 2
Ruby 4
Scripting 4
Statistics 2
Web 3

在上面的输出中,我还想要百分比,即第一行 5*100/219 等等。我在做以下事情

 Publisher.groupby('Category')['Title'].agg({'Count':'count','Percentage':lambda x:x/x.sum()})

但是它给了我一个错误。请帮忙

最佳答案

我认为你可以使用:

P = Publisher.groupby('Category')['Title'].count().reset_index()
P['Percentage'] = 100 * P['Title'] / P['Title'].sum()

示例:

Publisher = pd.DataFrame({'Category':['a','a','s'],
'Title':[4,5,6]})

print (Publisher)
Category Title
0 a 4
1 a 5
2 s 6

P = Publisher.groupby('Category')['Title'].count().reset_index()
P['Percentage'] = 100 * P['Title'] / P['Title'].sum()
print (P)
Category Title Percentage
0 a 2 66.666667
1 s 1 33.333333

关于python - 如何在 Python 中计算 groupby 中的计数和百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39893148/

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