1

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

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

4

2 回答 2

3

这是一种方法,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
于 2016-12-31T08:18:00.703 回答
1

只需使用滚动相关,具有非常大的窗口,并且 min_period = 1。

于 2020-06-24T08:05:31.813 回答