英文:
pandas groupby week and rolling
问题
我想按名称和周进行分组,然后按周获取滚动视图。预期输出如下:
name one_week_view two_weeks_view three_weeks_wiew
bag 80 170 270
phone 200 600 1050
英文:
i have a dataframe like this:
dfx=pd.DataFrame({"name":["bag","bag","bag","phone","phone","phone"],'date':["2022-11-14 00:00:00","2022-11-21 00:00:00","2022-11-28 00:00:00","2022-11-14 00:00:00","2022-11-21 00:00:00","2022-11-28 00:00:00"],"view":[80,90,100,200,400,450]})
'''
name date view
0 bag 2022-11-14 00:00:00 80
1 bag 2022-11-21 00:00:00 90
2 bag 2022-11-28 00:00:00 100
3 phone 2022-11-14 00:00:00 200
4 phone 2022-11-21 00:00:00 400
5 phone 2022-11-28 00:00:00 450
'''
I would like to group by name and week and get rolling views by week. Expected output:
name one_week_view two_weeks_view three_weeks_wiew
bag 80 170 270
phone 200 600 1050
答案1
得分: 2
已经有每周数据的情况下,您可以使用pivot
和cumsum
:
(dfx.pivot(index='name', columns='date', values='view')
.cumsum(axis=1)
.set_axis(['one_week_view', 'two_weeks_view', 'three_weeks_view'], axis=1)
)
输出:
one_week_view two_weeks_view three_weeks_view
name
bag 80 170 270
phone 200 600 1050
英文:
Given you already have weekly data, you could use a pivot
and cumsum
:
(dfx.pivot(index='name', columns='date', values='view')
.cumsum(axis=1)
.set_axis(['one_week_view', 'two_weeks_view', 'three_weeks_view'], axis=1)
)
Output:
one_week_view two_weeks_view three_weeks_view
name
bag 80 170 270
phone 200 600 1050
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论