【问题标题】:Python pandas has no attribute ols - Error (rolling OLS)Python pandas 没有属性 ols - 错误(滚动 OLS)
【发布时间】:2017-06-22 18:58:18
【问题描述】:

对于我的评估,我想运行一个滚动 1000 窗口 OLS regression estimation 在此 URL 中找到的数据集: https://drive.google.com/open?id=0B2Iv8dfU4fTUa3dPYW5tejA0bzg 使用以下Python 脚本。

# /usr/bin/python -tt

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from statsmodels.formula.api import ols

df = pd.read_csv('estimated.csv', names=('x','y'))

model = pd.stats.ols.MovingOLS(y=df.Y, x=df[['y']], 
                               window_type='rolling', window=1000, intercept=True)
df['Y_hat'] = model.y_predict

但是,当我运行 Python 脚本时,我收到此错误:AttributeError: module 'pandas.stats' has no attribute 'ols'。这个错误可能来自我正在使用的版本吗?我的Linux节点上安装的pandas的版本是0.20.2

【问题讨论】:

标签: python python-3.x pandas linear-regression statsmodels


【解决方案1】:

pd.stats.ols.MovingOLS 在 Pandas 版本 0.20.0 中被删除

http://pandas-docs.github.io/pandas-docs-travis/whatsnew.html#whatsnew-0200-prior-deprecations

https://github.com/pandas-dev/pandas/pull/11898

对于像滚动回归这样明显的用例,我找不到“现成的”解决方案。

以下内容应该可以解决问题,而无需在更优雅的解决方案上投入太多时间。它使用numpy根据回归参数和滚动窗口中的X值计算回归的预测值。

window = 1000
a = np.array([np.nan] * len(df))
b = [np.nan] * len(df)  # If betas required.
y_ = df.y.values
x_ = df[['x']].assign(constant=1).values
for n in range(window, len(df)):
    y = y_[(n - window):n]
    X = x_[(n - window):n]
    # betas = Inverse(X'.X).X'.y
    betas = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
    y_hat = betas.dot(x_[n, :])
    a[n] = y_hat
    b[n] = betas.tolist()  # If betas required.

上面的代码相当于下面的代码,速度快了大约 35%:

model = pd.stats.ols.MovingOLS(y=df.y, x=df.x, window_type='rolling', window=1000, intercept=True)
y_pandas = model.y_predict

【讨论】:

  • 是的,这是我从上面的 cmets 中了解到的。那么,您知道我们如何将它与最新版本的Pandas 一起使用吗?
  • @DestaHaileselassieHagos 您希望滚动回归得到什么结果(例如斜率、截距、预测值等)
  • @Alexander,例如预测值。谢谢!
  • 我实际上将我的pandas 版本回滚到0.18.0 并且ols 现在正在工作。非常感谢!
  • @Lost1,不,它没有。
【解决方案2】:

deprecated 支持 statsmodels。

请看这里examples how to use statsmodels rolling regression

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 2013-02-12
    • 2017-11-29
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2014-06-18
    相关资源
    最近更新 更多