1

在 R 中,可以执行多重线性回归,例如

temp = lm(log(volume_1[11:62])~log(price_1[11:62])+log(volume_1[10:61]))

在 Python 中,可以使用 R 样式公式执行多元线性回归,所以我认为下面的代码应该也能正常工作,

import statsmodels.formula.api as smf
import pandas as pd
import numpy as np

rando = lambda x: np.random.randint(low=1, high=100, size=x)

df = pd.DataFrame(data={'volume_1': rando(62), 'price_1': rando(62)})

temp = smf.ols(formula='np.log(volume_1)[11:62] ~ np.log(price_1)[11:62] + np.log(volume_1)[10:61]', 
               data=df) 
# np.log(volume_1)[10:61] express the lagged volume

但我得到了错误

PatsyError: Number of rows mismatch between data argument and volume_1[11:62] (62 versus 51)
volume_1[11:62] ~ price_1[11:62] + volume_1[10:61]

我想不可能只回归列中的部分行,因为 data = df 有 62 行,而其他变量有 51 行。

有没有像 R 一样方便的回归方法?

df 类型是 pandas Dataframe,列名是 volume_1,price_1

4

1 回答 1

0

使用 patsy 存储库中的github 问题中的示例,这将是让您的 lag 列正常工作的方法。

import statsmodels.formula.api as smf
import pandas as pd
import numpy as np

rando = lambda x: np.random.randint(low=1, high=100, size=x)

df = pd.DataFrame(data={'volume_1': rando(62), 'price_1': rando(62)})

def lag(x, n):
    if n == 0:
        return x
    if isinstance(x,pd.Series):
        return x.shift(n)

    x = x.astype('float')
    x[n:] = x[0:-n]
    x[:n] = np.nan
    return x

temp = smf.ols(formula='np.log(volume_1) ~ np.log(price_1) + np.log(lag(volume_1,1))', 
               data=df[11:62]) 
于 2018-10-25T15:42:47.963 回答