Deprecated rolling window option in OLS from Pandas to Statsmodels

前端 未结 4 2035
轻奢々
轻奢々 2020-12-07 17:16

as the title suggests, where has the rolling function option in the ols command in Pandas migrated to in statsmodels? I can\'t seem to find it. Pandas tells me doom is in th

4条回答
  •  难免孤独
    2020-12-07 17:32

    For rolling trend in one column, one can just use:

    import numpy as np
    def calc_trend(window:int = 30):
        df['trend'] = df.rolling(window = window)['column_name'].apply(lambda x: np.polyfit(np.array(range(0,window)), x, 1)[0], raw=True)
    

    However, in my case I wasted to find a trend with respect to date, where date was in another column. I had to create the functionality manually, but it is easy. First, convert from TimeDate to int64 representing days from t_0:

    xdays = (df['Date'].values.astype('int64') - df['Date'][0].value) / (1e9*86400)
    

    Then:

    def calc_trend(window:int=30):
        for t in range(len(df)):
            if t < window//2:
                continue
            i0 = t  - window//2 # Start window
            i1 = i0 + window    # End window
            xvec = xdays[i0:i1]
            yvec = df['column_name'][i0:i1].values
            df.loc[t,('trend')] = np.polyfit(xvec, yvec, 1)[0]
    

提交回复
热议问题