'float' object has no attribute 'rolling' when using lambda function

Question:

So I’m trying to calculate the z score using the lambda function.

Here’s the code,

zscore_fun_improved = lambda x: ((x - x.rolling(window=200, min_periods=20).mean()) / x.rolling(window=200, min_periods=20).std())
df.Close.apply(zscore_fun_improved)

But it gives me the following error,

AttributeError: 'float' object has no attribute 'rolling'

What am I doing wrrong?

Asked By: Bucky

||

Answers:

If you pass a Series to apply, the (lambda) function receive a scalar (a float here). If you pass a DataFrame to apply, the (lambda) function receive a Series.

So you don’t need apply here:

zscore_fun_improved(df.Close)

Demo:

# DataFrame -> apply get Series
>>> df.apply(type)
open     <class 'pandas.core.series.Series'>
close    <class 'pandas.core.series.Series'>
dtype: object

# Series -> apply get scalar values
>>> df['close'].apply(type)
0    <class 'float'>
1    <class 'float'>
2    <class 'float'>
3    <class 'float'>
4    <class 'float'>
Name: close, dtype: object
Answered By: Corralien
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.