应用于自定义数据帧功能

2024-09-29 23:27:22 发布

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

我在尝试对pandas数据帧应用自定义滚动函数时遇到异常。例如:

import statsmodels.api as sm
import pandas as pd
import numpy as np

def univar_regr_beta(y, x):
    Y, X = y.as_matrix(), x.as_matrix()

    X = sm.add_constant(X)

    model = sm.OLS(Y, X)
    return model.fit().params[1]

df = pd.DataFrame(np.random.randn(20,3))
srs = pd.Series(np.random.randn(20))

# this returns a value e.g.: 0.06608957
univar_regr_beta(df[0], srs)

# and this returns a rolling sum dataframe
df.rolling(5, 5).apply(np.sum)

# but this breaks when attemp to get rolling beta
df.rolling(5, 5).apply(lambda x: univar_regr_beta(x, srs))

具体来说,我得到的例外是:

^{pr2}$

当每个列通过lambda传递到univar_reg_beta时,它看起来像是作为一个凹凸的数组而不是一个序列来传递。我不确定是否有更好的方法来实现滚动测试版,或者我只是错过了一些东西。在

感谢任何帮助。谢谢


Tags: importpandasdfmodelasnpthismatrix

热门问题