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

I have following output after grouping by

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

In the above output I want the percentage also i.e for the first row 5*100/219 and so on. I am doing following

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

But it gives me an error. Please help

解决方案

I think you can use:

P = Publisher.groupby('Category')['Title'].count().reset_index()

P['Percentage'] = 100 * P['Title'] / P['Title'].sum()

Sample:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值