我想计算数据框中两列的滚动排名相关性,但是 pandas 中当前的 rolling_corr 不支持排名相关性。我尝试使用 rolling_apply 实现滚动排名相关性,但没有任何成功的经验。似乎 rolling_apply 只将一个数组作为输入参数,而相关性需要两个数组。有没有聪明的方法可以使用 rolling_apply 或其他方法实现滚动排名相关性?如果可能的话,排名相关性会成为 rolling_corr 的不错补充。
我认为rolling_apply
不能用于执行滚动相关性,因为它似乎会将DataFrames分解为1维数组。可能有更好的方法来做到这一点,但其中一种解决方案是自己生成器以产生每个窗口的切片:
def window(length, size=2, start=0):
while start + size <= length:
yield slice(start, start + size)
start += 1
In [144]: from pandas import DataFrame
...: import numpy as np
...:
...: df = DataFrame(np.arange(10).reshape(2,5).T, columns=['a','b'])
...:
...: df.iloc[0,1] = -1 #still perfect with ranked correlation, but not with pearson's r
...:
...: for w in window(len(df), size=3):
...: df_win = df.iloc[w,:]
...: spearman = df_win['a'].rank().corr(df_win['b'].rank())
...: pearson = df_win['a'].corr(df_win['b'])
...: print w.start, spearman, pearson
...:
0 1.0 0.917662935482
1 1.0 1.0
2 1.0 1.0