我正在 Python Pandas 中处理一个名为 Gradedata.csv 的数据集,其中我创建了一个名为“状态”的新分箱列,如果成绩 > 70,则为“通过”;如果成绩 <= 70,则为“失败”。这是数据集前五行的列表:
fname lname gender age exercise hours grade \
0 Marcia Pugh female 17 3 10 82.4
1 Kadeem Morrison male 18 4 4 78.2
2 Nash Powell male 18 5 9 79.3
3 Noelani Wagner female 14 2 7 83.2
4 Noelani Cherry female 18 4 15 87.4
address status
0 9253 Richardson Road, Matawan, NJ 07747 Pass
1 33 Spring Dr., Taunton, MA 02780 Pass
2 41 Hill Avenue, Mentor, OH 44060 Pass
3 8839 Marshall St., Miami, FL 33125 Pass
4 8304 Charles Rd., Lewis Center, OH 43035 Pass
现在,我如何计算“状态”为及格的女学生的平均锻炼时间......? 我使用了下面的代码,但它不起作用。
print(df.groupby('gender', 'status')['exercise'].mean())
我是 Pandas 新手。请任何人帮我解决这个问题。
最佳答案
你们很接近。请注意,您的 groupby
键必须是映射、函数、标签或标签列表之一。。在本例中,您需要一个标签列表。例如:
res = df.groupby(['gender', 'status'])['exercise'].mean()
然后您可以通过pd.Series.get
提取您想要的结果:
query = res.get(('female', 'Pass'))
关于python - 如何对 Pandas 中的分类列执行 groupby 和 Mean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50679939/