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?
CodePudding user response:
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