pandas resample when cumulative function returns data frame

Viewed 1786

I would like to use resampling function from pandas but applying my own custom function. The problem I'm facing is that the custom function returns a pandas Data Frame instead of a single array.

The following example illustrate my problem:

>>> import pandas as pd
>>> import numpy as np
>>> def f(data):
...     return ((1+data).cumprod(axis=0)-1)
... 
>>> data = np.random.randn(1000,3)
>>> index = pd.date_range("20170101", periods = 1000, freq="B")
>>> df = pd.DataFrame(data= data, index =index) 

Now suppose I want to resample the business days to business end month frequency:

>>> resampler = df.resample("BM")

If I apply now the my function f I don't get the desired result. I would like to get the last row of my output from f.

>>> resampler.apply(f)

this is becaumes the cumprod in my function f returns a pandas data frame. I could write my f such that it returns just the last row. However, I would like to use this function in other places as well to return the whole Data Frame. This could be solved via introducing a flag like "last_row" in the function f which steers to return the complete or just the last row. But this solutions seem rather nasty.

2 Answers
Related