2021年3月30日星期二

Pandas rolling apply multiplication

I would have thought this would be a basic application of pd.DataFrame().rolling() or pd.Series().rolling(), but it appears that the pandas rolling function cannot handle scalar multiplication being applied to a rolling window; I am hoping I am wrong and someone can spot the error.

I am trying to take a rolling window of a series (or dataframe) and multiply each row of that series/dataframe by a series/dataframe of weights (these weights have been precomputed). The code I thought should work is:

data.rolling(5).apply( lambda x: x*weights )  

with

data = pd.Series( np.random.randint(1,101,2000) )    weights = pd.Series([ 0.10650, 0.1405310, 0.1854318, 0.2446788, 0.3228556 ])  

I thought, data.rolling(5).apply( lambda x: x*weights ) would produce a new rolling series, but the following error is returned everytime "TypeError: cannot convert the series to <class 'float'>".

I should note that the only reason that I am trying to multiply the weights is to apply a corr/cov/mean statistic on the new rolling seres/dataframe afterward...something like

rolling_weighted_corr  = data.rolling(5).apply( lambda x: x*weights ).corr()  

Does anyone know how to multiply (scalar) a series with a rolling series to produce a new rolling series?

https://stackoverflow.com/questions/66880196/pandas-rolling-apply-multiplication March 31, 2021 at 08:49AM

没有评论:

发表评论