pandas.core.window.Rolling.apply

The rolling function’s apply function.

param func
function

Must produce a single value from an ndarray input if raw=True or a single value from a Series if raw=False.

param raw
bool, default None
  • Falsepasses each row or column as a Series to the

    function.

  • True or Nonethe passed function will receive ndarray

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

The raw parameter is required and will show a FutureWarning if not passed. In the future raw will default to False.

New in version 0.23.0.

Arguments and keyword arguments to be passed into func.

return

Series or DataFrame Return type is determined by the caller.

Limitations

  • This function may reveal slower performance than Pandas* on user system. Users should exercise a tradeoff

    between staying in JIT-region with that function or going back to interpreter mode.

  • Supported raw only can be None or True. Parameters args, kwargs unsupported.

  • DataFrame/Series elements cannot be max/min float/integer. Otherwise SDC and Pandas results are different.

Examples

Calculate the rolling apply.
import numpy as np
import pandas as pd
from numba import njit


@njit
def series_rolling_apply():
    series = pd.Series([4, 3, 5, 2, 6])  # Series of 4, 3, 5, 2, 6

    def get_median(x):
        return np.median(x)

    out_series = series.rolling(3).apply(get_median)

    return out_series  # Expect series of NaN, NaN, 4.0, 3.0, 5.0


print(series_rolling_apply())
$ python ./series/rolling/series_rolling_apply.py
0    NaN
1    NaN
2    4.0
3    3.0
4    5.0
dtype: float64
Calculate the rolling apply.
import numpy as np
import pandas as pd
from numba import njit


@njit
def df_rolling_apply():
    df = pd.DataFrame({'A': [4, 3, 5, 2, 6], 'B': [-4, -3, -5, -2, -6]})

    def get_median(x):
        return np.median(x)

    out_df = df.rolling(3).apply(get_median)

    # Expect DataFrame of
    # {'A': [NaN, NaN, 4.0, 3.0, 5.0], 'B': [NaN, NaN, -4.0, -3.0, -5.0]}
    return out_df


print(df_rolling_apply())
$ python ./dataframe/rolling/dataframe_rolling_apply.py
     A    B
0  NaN  NaN
1  NaN  NaN
2  4.0 -4.0
3  3.0 -3.0
4  5.0 -5.0

See also

Series.rolling

Calling object with a Series.

DataFrame.rolling

Calling object with a DataFrame.

Series.apply

Similar method for Series.

DataFrame.apply

Similar method for DataFrame.