Python pandas没有属性ols - 错误(滚动OLS)

Des*_*gos 4 python linear-regression python-3.x pandas statsmodels

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

# /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
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*der 7

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.
Run Code Online (Sandbox Code Playgroud)

上面的代码相当于以下代码,速度提高了约35%:

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