pandas.api.typing.Rolling.apply#
- Rolling.apply(func, raw=False, engine=None, engine_kwargs=None, args=None, kwargs=None)[source]#
Calculate the rolling custom aggregation function.
Applies an arbitrary function to each rolling window. This is useful when the built-in rolling methods do not cover the desired computation.
- Parameters:
- funcfunction
Must produce a single value from an ndarray input if
raw=Trueor a single value from a Series ifraw=False. Can also accept a Numba JIT function withengine='numba'specified.- rawbool, default False
False: passes each row or column as a Series to the function.True: the passed function will receive ndarray objects instead. Pandas-only attributes such as.ilocor.indexare not available on ndarrays and will raiseAttributeErrorif used insidefunc.
If you are just applying a NumPy reduction function this will achieve much better performance.
- enginestr, default None
'cython': Runs rolling apply through C-extensions from cython.'numba': Runs rolling apply through JIT compiled code from numba. Only available whenrawis set toTrue.None: Defaults to'cython'or globally settingcompute.use_numba.
- engine_kwargsdict, default None
For
'cython'engine, there are no acceptedengine_kwargsFor
'numba'engine, the engine can acceptnogilandparalleldictionary keys. The values must either beTrueorFalse.
The default
engine_kwargsfor the'numba'engine is{'nogil': False, 'parallel': False}and will be applied to both thefuncand theapplyrolling aggregation.- argstuple, default None
Positional arguments to be passed into func.
- kwargsdict, default None
Keyword arguments to be passed into func.
- Returns:
- Series or DataFrame
Return type is the same as the original object with
np.float64dtype.
See also
Series.rollingCalling rolling with Series data.
DataFrame.rollingCalling rolling with DataFrames.
Series.applyAggregating apply for Series.
DataFrame.applyAggregating apply for DataFrame.
Notes
When
raw=False, theSeriespassed tofuncis indexed by the column orIndexused to compute the rolling window. IfDataFrame.rolling()was called withon=col, the index of the passedSerieswill be the values ofcolrather than the originalDataFrameindex. Whenonis not specified, the index of the passedSeriesis the original index of the input.Examples
>>> ser = pd.Series([1, 6, 5, 4]) >>> ser.rolling(2).apply(lambda s: s.sum() - s.min()) 0 NaN 1 6.0 2 6.0 3 5.0 dtype: float64