加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用pandas按组获取计数

发布时间:2020-12-16 21:38:19 所属栏目:Python 来源:网络整理
导读:参见英文答案 How to pivot a dataframe1个 我有一个pandas数据框,其中包含如下所示的数据: ID year_month_id Class1 201612 A2 201612 D3 201612 B4 201612 Other5 201612 Other6 201612 Other7 201612 A8 201612 Other9 201612 A1 201701 B 因此,ID可以在
参见英文答案 > How to pivot a dataframe1个
我有一个pandas数据框,其中包含如下所示的数据:
ID  year_month_id   Class
1   201612          A
2   201612          D
3   201612          B
4   201612          Other
5   201612          Other
6   201612          Other
7   201612          A
8   201612          Other
9   201612          A
1   201701          B

因此,ID可以在特定月份的任何课程中,下个月他的课程可能会发生变化.
现在我要做的是为每个ID获取它在特定类下的月数以及它所属的最新类.如下所示:

ID  Class_A Class_B Class_D Other Latest_Class
1   2        3       4         0    B
2   12       0       0         0    D

我如何在python中实现这一点.
有人可以帮我这个吗?
此外,由于真实数据集很大并且无法手动验证,我如何才能获得超过1类的ID列表?

解决方法

我们可以使用数据透视表和concat,即
ndf = df.pivot_table(index=['ID'],columns=['Class'],aggfunc='count',fill_value=0)
    .xs('year_month_id',axis=1,drop_level=True)

ndf['latest'] = df.sort_values('ID').groupby('ID')['Class'].tail(1).values

Class  A  B  D  Other latest
ID                          
1      1  1  0      0      B
2      0  0  1      0      D
3      0  1  0      0      B
4      0  0  0      1  Other
5      0  0  0      1  Other
6      0  0  0      1  Other
7      1  0  0      0      A
8      0  0  0      1  Other
9      1  0  0      0      A

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读