Saturnix
Saturnix

Reputation: 10554

Pandas, call custom function on rolling

I have a function my_function(data) that takes in data a Python array (or Numpy serie) and returns an integer.

I could feed to this function a column from a Pandas dataframe and I would get the my_function of the entire series.

Now I would like to do that but on a rolling basis.

my_function(data['column'].rolling(30)) simply won't work because the function wants an array. Same goes for data['column'].rolling(30).my_function.

What's the syntactically correct way to do this? Is it possible? Or do I have to do that manually?

If I have to loop over the dataframe by myself, is there anything I can use so that each iteration gives me an arbitrary number of rows at a time (lets say 30)?

Upvotes: 0

Views: 125

Answers (1)

jezrael
jezrael

Reputation: 863751

Use Rolling.apply:

data['column'].rolling(30).apply(my_function)

Also help How do pandas Rolling objects work?.

Upvotes: 2

Related Questions