我一直在寻找最新的方法来创建一个给定熊猫数据帧的线性回归模型。在
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列:
^{pr2}$我希望能够创建一个线性回归,它使用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创建两个回归模型(红线是分组int1的值,靛蓝线是分组int2的值)
提前谢谢!在
这是我能够解决的“解决方案”:
首先,我只想要第1-52周,不包括0或53周。在
然后,我创建了一个列,使用dt.to_period功能将所有日期按一年中的星期按顺序分组:
^{pr2}$这是一个有点迂回的地方。首先,按周创建一组有序的时间段集:
其次,创建一个字典,其中按时间顺序排列的时间段按顺序编号:
最后,向dataframe添加一个新列,其中每个数据点都从有序字典中给定数字(0,n):
其中函数
apply_order
只是一个字典查找:然后,对于线性回归:
我希望这对某些人有帮助!在
相关问题 更多 >
编程相关推荐