【问题标题】:pandas group by on column values and get count熊猫按列值分组并获取计数
【发布时间】:2021-10-30 09:20:24
【问题描述】:

我有结果、学生、版本和状态列。在这个我想通过使用 Student , Version 和 result = pass count 和 result = fail count 来分组

类似于 df.groupby(["student", "version", "result=pass"]).size().reset_index(name="new_result")

下面是我的数据框

result student version status
pass Student-A L-1.0 Active
fail Student-A L-1.0 Active
fail Student-A L-1.0 Active
pass Student-A M-1.0 Active
fail Student-A M-1.0 Active
pass Student-B N-1.0 Active
pass Student-B N-1.0 Active
pass Student-B N-1.0 Active
pass Student-C O-1.0 Active
pass Student-C O-1.0 Active
fail Student-C O-1.0 Active
fail Student-C P-1.0 Active
fail Student-C P-1.0 Active

我希望我的输出数据框如下:

student version pass_count fail_count status total_count (pass+fail)
Student-A L-1.0 1 2 Active 3
Student-A M-1.0 1 1 Active 2
Student-B N-1.0 3 0 Active 3
Student-C O-1.0 1 1 Active 2
Student-C P-1.0 0 2 Active 2

我可以使用以下但不是总计数来获得通过和失败计数,请任何人帮助

pd.pivot_table(master_df, index=['status', 'student', 'version'], columns=['result'], aggfunc=len, fill_value=0)

【问题讨论】:

  • 尝试使用 df.pivot_table 来做上述情况。
  • @Roxy,我对 pivot_table 不熟悉,请您帮忙提供一些参考代码或者可能是确切的代码
  • 我可以使用以下但不是总计数来获得通过和失败计数,任何人请帮助 pd.pivot_table(master_df, index=['status', 'student', 'version'], columns=['result'], aggfunc=len, fill_value=0)
  • 您需要提供示例数据,以便我们重新创建问题。
  • 查看下面的代码以获取总数

标签: python pandas group-by


【解决方案1】:

如果要获取总数,可以使用:

df.groupby(["student", "version"])['result'].count().reset_index(name='total_count')

结果:

     student version  total_count
0  Student-A   L-1.0            3
1  Student-A   M-1.0            2
2  Student-B   N-1.0            3
3  Student-C   O-1.0            3
4  Student-C   P-1.0            2

或者,如果您想根据数据透视表获取它,您可以使用:

df2 = pd.pivot_table(df, index=['status', 'student', 'version'], columns=['result'], aggfunc=len, fill_value=0).reset_index().rename_axis(columns=None)

df2['total_count'] = df2['fail'] + df2['pass']

结果:

print(df2)

   status    student version  fail  pass  total_count
0  Active  Student-A   L-1.0     2     1            3
1  Active  Student-A   M-1.0     1     1            2
2  Active  Student-B   N-1.0     0     3            3
3  Active  Student-C   O-1.0     1     2            3
4  Active  Student-C   P-1.0     2     0            2

【讨论】:

  • 非常感谢@seaBean,它完全按照我的要求工作,非常感谢您的支持。欢呼
  • @user3202086 欢迎您!乐于助人!快乐编程,祝你有美好的一天! :-)
  • 在上表中,我还有一个名为“失败科目”的列,其中提到了每个学生失败的科目,所以我希望输出如下 Active Student-A L-1.0 2 1 3 maths, Science
  • 你能帮我解决这个问题吗?
  • @user3202086 在这里评论中的几句话很难理解你的新数据结构。如果您可以使用带有示例数据的数据结构和基于示例数据的所需输出发布一个新问题,那就更好了。您可以在发布问题后在这里给我建议,如果可以的话,我会尽力看看。
猜你喜欢
  • 2021-11-18
  • 2021-11-11
  • 1970-01-01
  • 2018-09-30
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 2020-12-19
相关资源
最近更新 更多