繁体   English   中英

如何计算两列数据框分组中的百分比

[英]How to calculate a percentage in a dataframe grouping by two columns

我正在通过两个列“zone_id和eventName”上的数据框进行分组。我需要计算按zone_id分组的eventName的百分比。

换句话说,我需要通过zone_id计算(点击/打印)* 100。

import pandas as pd

#read the csv file
df = pd.read_csv('data.csv', sep=';')

result=df.groupby(['zone_id','eventName']).event.count()

print(result)

#I use count() method to extract the number of clicked and printed by zone_id. Then on this basis I think to be able to find a way to compute a     percentage by zone_id.

output : 
zone_id  eventName
28       printed         88
9283     clicked         197
         printed         7732
9284     clicked         2
         printed         452
9287     clicked         129
         printed         3802
9614     clicked         4
         printed         342
17437    clicked         55
         printed         4026

#By using mean() function, the mean calculation is well done grouped by zone_id
result=df.groupby(['zone_id','eventName']).event.count().groupby('zone_id').mean()

print(result)

output :
zone_id
28         88.0
9283     3964.5
9284      227.0
9287     1965.5
9614      173.0
17437    2040.5

#Expected result : I need to compute the percentage of eventName (clicked/printed)*100 by zone_id
 Expected output:
zone_id
28        0%    -> (0/88)*100
9283      2.54% -> (197/7732)*100
9284      0.44% -> (2/452)*100
9287      3.39% -> (129/3802)*100
9614      1.16% -> (4/342)*100
17437     1.36% -> (55/4026)*100

没有样本数据很难看到,但尝试这样的事情?

events = df.groupby(['zone_id','eventName']).size()
events.loc[pd.IndexSlice[:, 'printed']] / events.loc[pd.IndexSlice[:, 'clicked']]

或者使用unstack来获取单击并打印为列:

events = df.groupby(['zone_id','eventName']).size().unstack(level=1)
events['printed'] / events['clicked']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM