【问题标题】:Rolling Z-score applied to pandas dataframe滚动 Z 分数应用于熊猫数据框
【发布时间】:2020-04-23 02:24:19
【问题描述】:

我想为我的数据框中的一列计算滚动 Z 分数:

import pandas as pd

values = [1,2,3,4,5]

d1= {'vol': values}

df= pd.DataFrame(d1)

有没有类似的方法:

df['mean'] = df.rolling(2).mean()

也许有:

from scipy import stats
stats.zscore(df)

编辑:在类似的帖子中发现了这种方法:

def zscore_func(x):
    return (x[-1] - x[:-1].mean())/x[:-1].std(ddof=0)
df.rolling(window=3).apply(zscore_func)

【问题讨论】:

    标签: python pandas rolling-computation


    【解决方案1】:
    window = 2
    target_column = 'vol'
    roll = df[target_column].rolling(window)
    df['z-score'] = (df[target_column] - roll.mean()) / roll.std()
    

    【讨论】:

      【解决方案2】:

      这是for循环的一种解决方案

      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.])]
      

      【讨论】:

        猜你喜欢
        • 2021-09-24
        • 2021-03-31
        • 1970-01-01
        • 2012-11-04
        • 2018-11-13
        • 1970-01-01
        • 2014-10-05
        • 1970-01-01
        相关资源
        最近更新 更多