pandas按周分组和滚动

huangapple go评论61阅读模式
英文:

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

已经有每周数据的情况下,您可以使用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
英文:

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

huangapple
  • 本文由 发表于 2023年2月19日 17:55:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定