大熊猫“累积”rolling_corr

时间:2016-12-31 07:17:41

标签: python pandas rolling-computation

有没有内置的熊猫方法来找到两个熊猫系列之间的累积相关性?

它应该做的是在pandas.rolling_corr(数据,窗口)中有效地修复窗口的左侧,以便窗口的宽度增加,最终窗口包括所有数据点。

2 个答案:

答案 0 :(得分:1)

这是一种方式,map索引,并应用corr来增加系列的大小。

In [116]: df.index.map(lambda x: df[col1].corr(df.loc[:x, col2]))

详细

In [112]: df = pd.DataFrame(pd.np.random.rand(10,2))

In [113]: df
Out[113]:
          0         1
0  0.094958  0.891910
1  0.482616  0.551912
2  0.877540  0.573768
3  0.839921  0.328452
4  0.334714  0.908346
5  0.530518  0.837590
6  0.285152  0.126937
7  0.386568  0.474815
8  0.279807  0.939694
9  0.741882  0.135982

In [114]: df['roll_corr'] = df.index.map(lambda x: df[0].corr(df.loc[:x, 1]))

In [115]: df
Out[115]:
          0         1  roll_corr
0  0.094958  0.891910        NaN
1  0.482616  0.551912  -1.000000
2  0.877540  0.573768  -0.832929
3  0.839921  0.328452  -0.848385
4  0.334714  0.908346  -0.839698
5  0.530518  0.837590  -0.791736
6  0.285152  0.126937  -0.312806
7  0.386568  0.474815  -0.283357
8  0.279807  0.939694  -0.354385
9  0.741882  0.135982  -0.459907

验证

In [121]: df.corr()
Out[121]:
          0         1
0  1.000000 -0.459907
1 -0.459907  1.000000

In [122]: df[:5].corr()
Out[122]:
          0         1
0  1.000000 -0.839698
1 -0.839698  1.000000

答案 1 :(得分:1)

只需使用滚动相关性(窗口很大,且min_period = 1)即可。