【发布时间】:2019-12-13 03:23:40
【问题描述】:
我正在按两列“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
【问题讨论】:
-
您声明您想要“百分比”,但您似乎正在计算“比率”。百分比为
clicked/(clicked + printed) -
@ALollz 我假设您必须在打印之前单击 - 在这种情况下比例是正确的!
-
确实是计算比率而不是百分比。
标签: python python-3.x pandas dataframe pandas-groupby