【问题标题】:Linear Regression in Pandas Groupby with freq='W-MON'Pandas Groupby 中的线性回归,freq='W-MON'
【发布时间】:2019-10-14 06:52:24
【问题描述】:

我有超过一年的数据。我有兴趣按周对数据进行分组,并按周获得两个变量的斜率。以下是数据的样子:

Date               | Total_Sales| Products
2015-12-30 07:42:50| 2900       | 24
2015-12-30 09:10:10| 3400       | 20
2016-02-07 07:07:07| 5400       | 25
2016-02-07 07:08:08| 1000       | 64

因此,理想情况下,我希望每周对该数据的 total_sales 和 products 执行线性回归并记录斜率。这在数据中表示每周时有效,但是当数据中跳过了几周时我遇到了问题。我知道我可以通过将日期转换为周数来做到这一点,但我觉得结果会出现偏差,因为有超过一年的数据。

这是我目前的代码:

df['Date']=pd.to_datetime(vals['EventDate']) - pd.to_timedelta(7,unit='d')
df.groupby(pd.Grouper(key='Week', freq='W-MON')).apply(lambda v: linregress(v.Total_Sales, v.Products)[0]).reset_index()

但是,我收到以下错误:

ValueError: Inputs must not be empty.

我希望输出如下所示:

Date       | Slope
2015-12-28 | -0.008     
2016-02-01 | -0.008

【问题讨论】:

    标签: python python-3.x timestamp linear-regression pandas-groupby


    【解决方案1】:

    我认为这是因为 python 无法正确分组,也无法将日期时间识别为键,因为日期列也有不同的时间戳。

    试试下面的代码。它对我有用:

    df['Date']=pd.to_datetime(df['Date'])  #### Converts Date column to Python Datetime
    
    df['daysoffset'] = df['Date'].apply(lambda x: x.weekday())
    #### Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
    
    df['week_start'] = df.apply(lambda x: x['Date'].date()-timedelta(days=x['daysoffset']), axis=1)  
    #### x.['Date'].date() removes timestamp and considers only Date
    #### the line assigns date corresponding to last Monday to column 'week_start'.
    
    
    df.groupby('week_start').apply(lambda v: stats.linregress(v.Total_Sales,v.Products) 
    [0]).reset_index()
    

    【讨论】:

      猜你喜欢
      • 2017-05-21
      • 2023-03-13
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多