python - 使用 Pandas 按组获取计数

标签 python pandas dataframe group-by pandas-groupby

<分区>

我有一个 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 可以在特定月份的任何类(class)下,下个月他的类(class)可能会改变。 现在我想要做的是为每个 ID 获取它在特定类别下的月数以及它所属的最新类别。如下所示:

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

我如何在 python 中实现这一点。 有人可以帮我吗? 另外,由于真实的数据集很大,无法手动验证,我如何才能获得属于多个类别的 ID 列表?

最佳答案

我们可以使用数据透视表和连接,即

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 - 使用 Pandas 按组获取计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47906226/

相关文章:

python - 从 JSON 文件加载数据

python - 如何直接在 Pandas DataFrame 中的 PDF 上计算统计指标?

python - 具有相同颜色和标记的散点图子图

pandas - 使用 loc 的 bool 索引返回 NaN

python - 如何逐行读取文本文件并针对特定行执行某些操作?

python - 更改anaconda中的默认环境

python - 在 Python 中,如何搜索过去 24 小时内创建的文件?

python - 仅从列表理解中打印非空数据框

python - 根据另一个数据框转换一列列表

python - 在数据帧字典上生成平均值