[英]how to create column that count number of rows per each date of id
I have df like this我有这样的df
id datetime
0 a 2022-01-18
1 a 2022-01-19
2 a 2022-01-20
3 b 2022-01-20
4 b 2022-01-20
5 c 2022-01-18
and I want df which looks something like我想要 df 看起来像
id 2022-01-20 2022-01-19 2022-01-18
0 a 1 1 1
1 b 2 0 0
2 c 0 0 1
I've tried我试过了
df.groupby(['id', 'datetime']).size()
id datetime
a 2022-01-18 1
2022-01-19 1
2022-01-20 1
b 2022-01-20 2
c 2022-01-18 1
it returns series not dataframe which is close but still not what I want.它返回系列不是 dataframe 接近但仍然不是我想要的。 pls help
请帮忙
You can do that with the following code您可以使用以下代码执行此操作
df = df.groupby(['id','date']).size().unstack(fill_value=0).reset_index()
df.columns.name = None
And as a result结果
df.head()
id 2022-01-18 2022-01-19 2022-01-20
0 a 1 1 1
1 b 0 0 2
2 c 1 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.