【问题标题】:Evaluating the percentage of True for a unique value in a column评估列中唯一值的 True 百分比
【发布时间】:2019-11-11 08:45:19
【问题描述】:
我有一个包含几个列的数据集,我想评估其中的 2 个。其中一列显示 0 到 1 之间的整数,另一列给出品牌名称。我想知道如何获得第 1 列对于品牌列的每个唯一值都有 1 的次数。
例如:
Sold out Brand
1 Twinkies
1 kitkat
0 Twinkies
0 Nerds
0 Rice krispies
0 Twinkies
1 snickers
结果可能是:
双胞胎:33% - 1/3
奇巧:100% - 1/1
书呆子:0% - 0/1
米脆饼 0% - 0/1
【问题讨论】:
标签:
python
python-3.x
pandas
validation
【解决方案1】:
你可以使用函数groupby():
g = df.groupby('Brand')
g['Sold out'].sum() / g['Brand'].size() * 100
输出:
Brand
Nerds 0.000000
Rice 0.000000
Twinkies 33.333333
kitkat 100.000000
snickers 100.000000
dtype: float64
【解决方案2】:
使用GroupBy.mean - 它是1 值的数量除以计数:
s = df.groupby('Brand')['Sold out'].mean().mul(100)
print (s)
Brand
Nerds 0.000000
Rice krispies 0.000000
Twinkies 33.333333
kitkat 100.000000
snickers 100.000000
Name: Sold out, dtype: float64