python-3.x Pandas按周和滚动分组

dbf7pr2w  于 2023-02-20  发布在  Python
关注(0)|答案(1)|浏览(142)

我有这样一个 Dataframe :

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
'''

我想按名称和周分组,并按周滚动视图。预期输出:

name  one_week_view  two_weeks_view  three_weeks_wiew
bag   80             170              270  
phone 200            600              1050
jgwigjjp

jgwigjjp1#

如果您已经有了每周数据,则可以使用pivotcumsum

(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

相关问题