【问题标题】:pandas, grouping data by weekpandas,按周分组数据
【发布时间】:2019-08-08 00:11:57
【问题描述】:

一年大约有 54 周。

我想得到每个弱者的销售额总和。

给定一个时间序列数据(带有日期时间或 unixtime) (我的数据看起来像:

 userId,movieId,rating,timestamp
 1,31,2.5,1260759144

)

我希望输出如下所示

1week (1/1 - 1/7) : 30$
2week (1/8 - 1/14) : 40$
...
54week (12/24 - 12/31) : 50$

我输入的日期(1/1 等)只是为了解释,我想获得每周组(以获得季节性指数),它不必从 1/1 或类似的东西开始。 .

数据可能包含多年。

  • 编辑

我想在多年内按周进行分组,就像您可以在多年内按月 [一月、二月、......十二月] 进行分组(多年数据为 12 组)。

【问题讨论】:

    标签: pandas


    【解决方案1】:

    通过week 使用Series.resample 和聚合函数 - 例如mean

    rng = pd.date_range('2017-04-03', periods=10)
    s = pd.DataFrame({'a': range(10)},index=rng)['a']
    print (s)
    2017-04-03    0
    2017-04-04    1
    2017-04-05    2
    2017-04-06    3
    2017-04-07    4
    2017-04-08    5
    2017-04-09    6
    2017-04-10    7
    2017-04-11    8
    2017-04-12    9
    Freq: D, Name: a, dtype: int64
    
    s1 = s.resample('W').mean()
    #alternative
    #s1 = s.groupby(pd.Grouper(freq='W')).mean()
    print (s1)
    2017-04-09    3
    2017-04-16    8
    Freq: W-SUN, Name: a, dtype: int64
    

    替代方案:

    s1 = s.groupby(s.index.strftime('%Y-%U')).mean()
    print (s1)
    2017-14    2.5
    2017-15    7.5
    Name: a, dtype: float64
    

    编辑:

    样本数据需要预处理:

    print (df)
       userId  movieId  rating   timestamp
    0       1       31     2.5  1260759144
    1       1       31     2.5  1560759144
    
    
    df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')
    
    w = df['timestamp'].rename('week').dt.weekofyear
    df = df['rating'].groupby(w).mean().reset_index(name='val')
    print (df)
       week  val
    0    25  2.5
    1    51  2.5
    

    【讨论】:

    • 谢谢!,我之前没有使用过 DatetimeIndex,(我添加了我的数据如何操作)并试图解密我如何应用它。如果数据包含 2017 年和 2018 年的数据,是否将一年中的第一周归为一组?
    • @eugene - 所以,我认为 DatetimeIndex,因为标题是 timeseries :)
    • @eugene - 所以这取决于 - 我的经验是 resample 应该更准确,但还添加了替代解决方案 - 通过 strftimeDatetimeIndex 转换为字符串。最好比较两种解决方案。
    • 您能告诉我如何将您的方法应用于我的数据格式吗? :( 我确信它会解决我的问题,但我需要一些时间来了解正在发生的事情
    • 是的,我做到了df['date'] = pd.to_datetime(df['timestamp'], unit='s') ;df.resample('w', on='date').mean(),谢谢! .. 一件事似乎,它似乎不处理多年的数据,所以我需要在完成resample
    【解决方案2】:

    您可以先创建一个星期列,pandas 的 to_datetime 真的很有用

    df['week'] = pd.to_datetime(df['timestamp']).dt.week
    df['year'] = pd.to_datetime(df['timestamp']).dt.year
    weekly_sales = df.groupby(['year','week'])['sales'].sum()
    

    【讨论】:

    • 感谢您的帮助!但由于某种原因,df['week'] 似乎每一行都是 1
    • @eugene 没有时间戳很难判断,日期会改变吗?
    猜你喜欢
    • 2016-11-04
    • 1970-01-01
    • 2020-07-23
    • 2021-06-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    相关资源
    最近更新 更多