【问题标题】:Pandas ordinary linear regression based on dt year-weeknumber (as of 2018)?Pandas 基于 dt year-weeknumber 的普通线性回归(截至 2018 年)?
【发布时间】:2018-06-25 13:30:27
【问题描述】:

我一直在寻找在给定 Pandas Dataframe 的情况下创建线性回归模型的最新方法。

DF 看起来像:

+---------------------+-------------+--------------------+--------------------+
|        Date         | YearWeekNum | Dependent_Variable | Bonus_Grouping_Int |
+---------------------+-------------+--------------------+--------------------+
| 2017-07-01 00:12:07 | 2017-Wk26   |               35.4 |                  1 |
| 2017-07-01 00:12:07 | 2017-Wk26   |               33.3 |                  2 |
| 2018-01-05 25:12:07 | 2018-Wk0    |               28.2 |                  1 |
| 2018-01-05 25:12:07 | 2018-Wk0    |               24.2 |                  2 |
+---------------------+-------------+--------------------+--------------------+

我创建了 YearWeekNum 列:

df['YearWeekNum'] = df['Date'].dt.strftime('%Y-Wk%U')

我希望喜欢能够创建一个线性回归,它使用YearWeekNum 作为独立(预测)变量,Dependent Variable 作为(你猜对了)依赖(响应) 多变的。最后的情节是这样的:

我尝试了this question,使用result = sm.ols(formula="Dependent_Variable ~ YearWeekNum", data=df).fit(),但它创建了一个以每个 YearWeekNum 作为其自变量的模型(对每个周期间进行回归。

从这个one,我也试过了:

from pandas.stats.api import ols

但是得到了:

ImportError: cannot import name 'ols'

似乎 ols 已被弃用。所以,我的问题是:如何使用 Pandas 以年份和周数作为自变量对数据框进行线性回归?

Cherry on top:将基于分组 int 创建两个回归模型(红线是 Grouping int 1 的值,靛蓝线是 Grouping int 2 的值)

提前致谢!

【问题讨论】:

    标签: python pandas linear-regression


    【解决方案1】:

    这是我能够完成的“解决方案”:

    首先,我只想要第 1-52 周,而不是第 0 周或第 53 周。

    df['YearWeekNum'] = df['Date'].dt.strftime('%Y-Wk%U')
    df.loc[df['YearWeekNum'].str.contains('Wk53') == True, 'YearWeekNum'] = '2017-Wk52'
    df.loc[df['YearWeekNum'].str.contains('Wk00') == True, 'YearWeekNum'] = '2018-Wk01'
    

    然后,我创建了一个列,使用dt.to_period 功能将所有日期按一年中的一周顺序分组:

    df['time_period'] = df['instrumentstartedon'].dt.to_period(freq='W')
    

    这是一个有点迂回的地方。首先,按周创建一组有序的时间段:

    dictionary_of_time_periods = dict()
    set_of_periods = set(df['time_period'])
    ordered_list_of_set = list(set_of_periods)
    ordered_list_of_set.sort()
    

    其次,创建一个字典,其中按时间顺序排列的时间段被赋予序号:

    index_key = 0
    
    # The following loop creates a dictionary of each time period (weeks by default)
    # which is used to create a consecutive sequence (1,n) for each week.
    # This dictionary is passed into the "apply_order" function which adds the column
    # to the DataFrame
    for t_period_pair in ordered_list_of_set:
        this_per = ordered_list_of_set[index_key]
        dictionary_of_time_periods[this_per] = (index_key + 1)
        index_key += 1
    

    最后,向数据框中添加一个新列,其中每个数据点都被赋予了有序字典中的数字 (0,n):

    df['ordered_nums'] = df.apply(lambda to_column: apply_order(to_column['time_period'], dictionary_of_time_periods),
                                  axis=1)
    

    函数apply_order 只是一个字典查找:

    def apply_order(df_like, dictionary_of_timeframes):
        return dictionary_of_timeframes[df_like]
    

    那么,对于线性回归:

    import statsmodels.formula.api as smf
    import matplotlib.pyplot as plt
    
    plt.style.use('ggplot')
    regression_result = smf.ols(formula='Dependent_Variable ~ ordered_nums', data=df).fit()
    print(regression_result.summary())
    print(regression_result.params)
    
    regression_intercept = regression_result.params[0]
    regression_slope = regression_result.params[1]
    
    n_points = len(set(df['YearWeekNum']))
    plot_x_array = []
    for inty in range(0, (n_points + 2)):
        plot_x_array += [inty]
    
    ols_regression_y_hat = [regression_slope * i + regression_intercept for i in plot_x_array]
    ax.plot(plot_x_array, ols_regression_y_hat, c='xkcd:violet', label='Linear Regression')
    fig.legend()
    

    我希望这对某人有所帮助!

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 1970-01-01
      • 2023-03-13
      • 2021-08-02
      • 2019-01-24
      • 2020-10-28
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      相关资源
      最近更新 更多