Python pandas没有属性ols-Error(rolling ols)

2024-05-16 13:59:01 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的评估,我想运行一个滚动的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


Tags: csvimport版本脚本pandasdfmodelas
1条回答
网友
1楼 · 发布于 2024-05-16 13:59:01

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

相关问题 更多 >