As @BrenBarn commented, the rolling function needs to reduce a vector to a single number. The following is equivalent to what you were trying to do and help's highlight the problem.

zscore = lambda x: (x - x.mean()) / x.std()
tmp.rolling(5).apply(zscore)
TypeError: only length-1 arrays can be converted to Python scalars

In the zscore function, x.mean() reduces, x.std() reduces, but x is an array. Thus the entire thing is an array.


The way around this is to perform the roll on the parts of the z-score calculation that require it, and not on the parts that cause the problem.

(tmp - tmp.rolling(5).mean()) / tmp.rolling(5).std()

Answer from piRSquared on Stack Overflow
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 2.2 › reference › api › pandas.core.window.rolling.Rolling.apply.html
pandas.core.window.rolling.Rolling.apply — pandas 2.2.3 documentation
Calculate the rolling custom aggregation 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. ... False : passes each row or column as a Series to the function. True : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance.
🌐
Statology
statology.org › home › how to use the rolling.apply() function in pandas
How to Use the Rolling.apply() Function in Pandas
April 17, 2024 - Often you may want to calculating some rolling value based on a custom function in a pandas DataFrame. The easiest way to do so is by using the Rolling.apply() function, which uses the following syntax:
🌐
Intelpython
intelpython.github.io › sdc-doc › latest › _api_ref › pandas.core.window.Rolling.apply.html
pandas.core.window.Rolling.apply — Intel® Scalable Dataframe Compiler 0.1 documentation
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 ·
🌐
Vultr Docs
docs.vultr.com › python › third party › pandas › dataframe › rolling()
Python Pandas DataFrame rolling() - Apply Rolling Function
December 24, 2024 - Define your own custom rolling function. Apply it using the apply() method on the rolling object.
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.rolling.html
pandas.DataFrame.rolling — pandas 3.0.6 documentation
Execute the rolling operation per single column or row ('single') or over the entire object ('table'). This argument is only implemented when specifying engine='numba' in the method call. Returns: pandas.api.typing.Window or pandas.api.typing.Rolling · An instance of Window is returned if win_type is passed.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.17.0 › generated › pandas.rolling_apply.html
pandas.rolling_apply — pandas 0.17.0 documentation
pandas.rolling_apply(arg, window, func, min_periods=None, freq=None, center=False, args=(), kwargs={})¶ · Generic moving function application. Notes · By default, the result is set to the right edge of the window. This can be changed to the center of the window by setting center=True.
🌐
Python Programming
pythonprogramming.net › rolling-apply-mapping-functions-data-analysis-python-pandas-tutorial
p.15 Data Analysis with Python and Pandas Tutorial
Since mapping functions is one of the two major ways that users can dramatically customize what Pandas can do, we might as well cover the second major way, which is with rolling_apply. This allows us to do a moving window application of a function.
Find elsewhere
🌐
Pandas
pandas.pydata.org › pandas-docs › stable › reference › api › pandas.core.window.rolling.Rolling.apply.html
pandas.core.window.rolling.Rolling.apply — pandas 2.3.3 documentation
Calculate the rolling custom aggregation 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. ... False : passes each row or column as a Series to the function. True : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.18.1 › generated › pandas.core.window.Rolling.apply.html
pandas.core.window.Rolling.apply — pandas 0.18.1 documentation
pandas.core.window.Rolling.apply · pandas.core.window.Rolling.quantile · pandas.core.window.Window.mean · pandas.core.window.Window.sum · Standard expanding window functions · Exponentially-weighted moving window functions · GroupBy · Resampling · Style · General utility functions ·
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 2.1 › reference › api › pandas.core.window.rolling.Rolling.apply.html
pandas.core.window.rolling.Rolling.apply — pandas 2.1.4 documentation
Calculate the rolling custom aggregation 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. ... False : passes each row or column as a Series to the function. True : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance.
🌐
Medium
medium.com › @whyamit101 › understanding-pandas-rolling-f8f6d6796c07
Understanding Pandas Rolling. If you think you need to spend $2,000… | by why amit | Medium
February 26, 2025 - You can even create custom aggregation functions using apply() to tailor the calculations to your needs. There you have it — moving averages, cumulative sums, and custom functions are just a few of the many ways you can take advantage of rolling ...
🌐
Delft Stack
delftstack.com › home › howto › python pandas › pandas use rolling apply
How to Use of rolling().apply() on Pandas Dataframe and Series | Delft Stack
February 2, 2024 - We use apply() function to apply a custom function (which is calculate_median() in our case) on the specified data. import pandas as pd import numpy as np points_df = pd.DataFrame( { "Team_A": [12, 23, 34, 45, 32, 45, 32, 21, 33], "Team_B": ...
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.api.typing.Rolling.apply.html
pandas.api.typing.Rolling.apply — pandas 3.0.3 documentation
Calculate the rolling custom aggregation 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. ... False : passes each row or column as a Series to the function. True : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.23.3 › generated › pandas.core.window.Rolling.apply.html
pandas.core.window.Rolling.apply — pandas 0.23.3 documentation
Extending Pandas · Release Notes · Enter search terms or a module, class or function name. Rolling.apply(func, raw=None, args=(), kwargs={})[source]¶ · rolling function apply · See also · pandas.Series.rolling, pandas.DataFrame.rolling · index · modules | next | previous | pandas 0.23.3 documentation » ·
🌐
Kanoki
kanoki.org › pandas-rolling-apply-custom-func-and-rolling-mean
Pandas rolling apply custom functions and statistical operations such as rolling mean(), max(), count(), sum(), median() agg() | kanoki
November 21, 2022 - We want to get the difference between the first and second row in each rolling window. The apply() function with lambda function uses iloc to get the first and second row and computes the difference between them
🌐
Programiz
programiz.com › python-programming › pandas › methods › rolling
Pandas rolling()
The rolling() method returns an object, which is not a final computed result but rather an intermediate object that allows us to apply various aggregation functions within the rolling window. import pandas as pd # create a DataFrame with sequential data data = pd.DataFrame({'value': [1, 2, ...
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 0.23.1 › generated › pandas.core.window.Rolling.apply.html
pandas.core.window.Rolling.apply — pandas 0.23.1 documentation
Extending Pandas · Release Notes · Enter search terms or a module, class or function name. Rolling.apply(func, raw=None, args=(), kwargs={})[source]¶ · rolling function apply · See also · pandas.Series.rolling, pandas.DataFrame.rolling · index · modules | next | previous | pandas 0.23.1 documentation » ·