python – 使用pandas按组获取计数

前端之家收集整理的这篇文章主要介绍了python – 使用pandas按组获取计数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > 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

猜你在找的Python相关文章