我有这个数据集。
data = pd.DataFrame({'sex':['male','female','female','male'],
'class':[1,2,3,2],
'smoking':[12,22,33,9]
})
class sex smoking
0 1 male 12
1 2 female 22
2 3 female 33
3 2 male 9
我按性别和阶级分组:
smokers = data.groupby(['sex','class'])['smoking'].agg(sum)
sex class
female 2 22
3 33
male 1 12
2 9
现在,我想只计算男性吸烟者。
我知道我能做到:
male_smokers = data[data['sex'] == 'male'].groupby(['sex','class'])['smoking'].agg(sum)
但我希望能够这样做:
male_smokers = smokers[smokers['sex'] == 'male'].count()
这可能吗?(现在我正在接受' keyError'性别)