I'd like some feedback on how to optimize the following pandas computation:
We have a fixed index set I and a lookback. In addition we have a pd.Series index its median over lookback, index_MEDIAN, and a large list of pandas data frames. All series/dataframes have I as their index. Each dataframe has the column value. Let D be one such dataframe..
For every row of D we take the corresponding value m in index_MEDIAN and sum all value entries present in the lookback window, subject to the condition that the running value in the index series is greater than m. In other words whenever the Index value is greater than the median of the lookback we sum the corresponding value row in D.
To shed more light, here is a sketch of the implementation described above
def sumvals(x)
S = (D['value'].loc[x.index] >= self.index_median.loc[x.index[-1]])
return sum(S*(x-self.index_median.loc[x.index[-1]]))
D['value'].rolling(lookback).apply(sumvals)
The list of dataframes is quite huge and I've noticed this way of computing this quantity takes an excessive amount of time. I suspect the issue is related to the fact that this implementation uses .loc a lot. Hence
Is there another way to express this solution without having to reference an external Series so much?
Either way, any kind of optimization suggestion is welcome.
Edit. Here is an example dataset with the respective computation.
lookback = 3
Index = pd.Series([1,-2,8,-10,3,4,5, 10, -20, 3])
Index_median = Index.rolling(lookback).median
Values = pd.Series([1,2,2,3,0,9,10, 8, 20, 9])
The resulting computation on Values should yield
0 NaN
1 NaN
2 2.0
3 13.0
4 0.0
5 6.0
6 11.0
7 12.0
8 23.0
9 28.0
For example the value in the 5th row is 6. Why? The Index_median value in the 5th row is 3. The 3-lookback in the 5th row is the sequence 9 , 0, 3. The values >= are 3 and 9 so this comprises our sum for the 5th row 3-3+9-3 = 6. Similarly for the last row the index median is 3. The last three rows in Values are all greater than 3 and sum up to 34 - 3*3 = 28.