Applying a Custom Crop Function to a Data Frame

I get an exception when trying to apply a custom crop function to a pandas data frame. For instance:

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))

In particular, I get the following:

AttributeError: 'numpy.ndarray' object has no attribute 'as_matrix'

It appears that when each column is passed to univar_regr_beta via lambda, it is passed as a bumpy array, not a series. I'm not sure if there is a better way to achieve a moving beta, or if I just missed something.

Any help is appreciated. Thanks

+4
source share

Source: https://habr.com/ru/post/1683059/


All Articles