Pandas Rolling Apply custom

后端 未结 2 1477
野的像风
野的像风 2020-12-15 06:39

I have been following a similar answer here, but I have some questions when using sklearn and rolling apply. I am trying to create z-scores and do PCA with rolling apply, bu

2条回答
  •  死守一世寂寞
    2020-12-15 07:37

    Since x in lambda function represents a (rolling) series/ndarray, the lambda function can be coded like this (where x[-1] refers to current rolling data point):

    zscore = lambda x: (x[-1] - x.mean()) / x.std(ddof=1)
    

    Then it is OK to call:

    tmp.rolling(5).apply(zscore)
    

    Also noted that the degree of freedom defaults to 1 in tmp.rolling(5).std() In order to generate the same results as @piRSquared's, one has to specify the ddof for x.std(), which defaults to 0. --It took quite a while to figure this out!

提交回复
热议问题