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 Class_A Class_B Class_D Other Latest_Class 1 2 3 4 0 B 2 12 0 0 0 D 我如何在python中实现这一点. 解决方法
我们可以使用数据透视表和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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容