简体   繁体   English

pandas: pivot - 按多列分组

[英]pandas: pivot - group by multiple columns

df = pd.DataFrame({'id': ['id1', 'id1','id1', 'id2','id1','id1','id1'],
'activity':['swimming','running','jogging','walking','walking','walking','walking'],
'month':[2,3,4,3,4,4,3]})

pd.crosstab(df['id'], df['activity'])

I'd like to add another column for month in the output to get counts per user within each month for the respective activity.我想在 output 中为月份添加另一列,以获取每个用户在每个月内针对相应活动的计数。

df.set_index(['id','month'])['activity'].unstack().reset_index()

I get error.我得到错误。

edit: Expected output in the image.编辑:图像中应为 output。 I do not know how to create a table.我不知道如何创建表。

在此处输入图像描述

You can pass a list of columns to pd.crosstab :您可以将列列表传递给pd.crosstab

x = pd.crosstab([df["id"], df["month"]], df["activity"]).reset_index()
x.columns.name = None

print(x)

Prints:印刷:

    id  month  jogging  running  swimming  walking
0  id1      2        0        0         1        0
1  id1      3        0        1         0        1
2  id1      4        1        0         0        2
3  id2      3        0        0         0        1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM