Skip to main content
`Ctrl`+`K`

# pandas.api.typing.Rolling.apply

Rolling.apply(func, raw=False, engine=None, engine_kwargs=None, args=None, kwargs=None)

  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:
    func function

      Must produce a single value from an ndarray input if `raw=True` or a single value from a Series if `raw=False`. Can also accept a Numba JIT function with `engine='numba'` specified.

    raw bool, 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 `.iloc` or `.index` are not available on ndarrays and will raise `AttributeError` if used inside `func`.

      If you are just applying a NumPy reduction function this will achieve much better performance.

    engine str, default None

      - `'cython'` : Runs rolling apply through C-extensions from cython.

      - `'numba'` : Runs rolling apply through JIT compiled code from numba. Only available when `raw` is set to `True`.

      - `None` : Defaults to `'cython'` or globally setting `compute.use_numba`.

    engine_kwargs dict, default None

      - For `'cython'` engine, there are no accepted `engine_kwargs`

      - For `'numba'` engine, the engine can accept `nogil` and `parallel` dictionary keys. The values must either be `True` or `False`.

      The default `engine_kwargs` for the `'numba'` engine is `{'nogil': False, 'parallel': False}` and will be applied to both the `func` and the `apply` rolling aggregation.

    args tuple, default None

      Positional arguments to be passed into func.

    kwargs dict, default None

      Keyword arguments to be passed into func.

  Returns:
    Series or DataFrame

      Return type is the same as the original object with `np.float64` dtype.

  See also

  `Series.rolling`

    Calling rolling with Series data.

  `DataFrame.rolling`

    Calling rolling with DataFrames.

  `Series.apply`

    Aggregating apply for Series.

  `DataFrame.apply`

    Aggregating apply for DataFrame.

  Notes

  When `raw=False`, the `Series` passed to `func` is indexed by the column or `Index` used to compute the rolling window. If `DataFrame.rolling()` was called with `on=col`, the index of the passed `Series` will be the values of `col` rather than the original `DataFrame` index. When `on` is not specified, the index of the passed `Series` is 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

  By default `func` is applied to each column independently. Use `method="table"` (which requires `engine="numba"` and `raw=True`) to instead pass the whole `DataFrame` window to `func` as a single 2D ndarray, so the function can combine multiple columns. Here a rolling dot product of columns `A` and `B` is computed; the scalar result is broadcast across the columns.

      >>> df = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]})
      >>> def dot(window):
      ...     return (window[:, 0] * window[:, 1]).sum()
      >>> df.rolling(3, method="table").apply(
      ...     dot, engine="numba", raw=True
      ... )
            A     B
      0   NaN   NaN
      1   NaN   NaN
      2  22.0  22.0
      3  25.0  25.0
      4  22.0  22.0