Skip to content Skip to sidebar Skip to footer

Rolling Z-score Applied To Pandas Dataframe

I would like to compute a rolling Z-score for one of my columns in my dataframe: import pandas as pd values = [1,2,3,4,5] d1= {'vol': values} df= pd.DataFrame(d1) Is there a wa

Solution 1:

window = 2
target_column = 'vol'
roll = df[target_column].rolling(window)
df['z-score'] = (df[target_column] - roll.mean()) / roll.std()

Solution 2:

Here is one solution by for loop

n=2
[np.nan]*n+[stats.zscore(df.iloc[x:x+n,0]) for x in range(0,len(df)-n)]
[nan, nan, array([-1.,  1.]), array([-1.,  1.]), array([-1.,  1.])]

Post a Comment for "Rolling Z-score Applied To Pandas Dataframe"