[英]How to count percentage of certain values in column in group?
我有一個數據框:
id is_good
a1 1
a1 1
a1 0
bb 1
bb 0
bb 0
bb 0
我想為每個 id 計算 0 和 1 的百分比。 所以想要的結果是:
id is_good_perc
a1 0.67
bb 0.25
怎么做? 在groupby("id")
之后我該怎么辦?
一般情況:
df.groupby("id").is_good.value_counts(normalize=True)
# id is_good
# a1 1 0.666667
# 0 0.333333
# bb 0 0.750000
# 1 0.250000
# Name: is_good, dtype: float64
在你的情況下,因為你有二進制變量,我會利用@sushanth 在評論中的內容並使用df.groupby('id')['is_good'].mean()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.