【问题标题】:Calculating rolling correlation of pandas dataframes计算熊猫数据框的滚动相关性
【发布时间】:2019-08-07 14:42:26
【问题描述】:

是否可以使用 pandas 中的滚动窗口和相关函数将较短的数据帧或序列与较长的数据帧或序列进行相关,并沿着较长的时间序列得到结果?基本上做 numpy.correlate 方法所做的事情,但不是互相关,而是做成对相关。

x= [0,1,2,3,4,5,4,7,6,9,10,5,6,4,8,7]
y= [4,5,4,5]
print(x)
print(y)
corrs = []
for i in range(0,len(x)-3):
    corrs.append( np.corrcoef(x[i:i+4],y)[0,1] )

结果是:

[0.4472135954999579, 0.4472135954999579, 0.4472135954999579, 0.0, 0.8164965809277259, -0.4472135954999579, 0.8320502943378437, 0.0, -0.24253562503633297, 0.24253562503633297, -0.7683498199278325, 0.8451542547285166, -0.50709255283711]

windows 和 pairwise 的每个组合要么给出一系列 NAN,要么给出“ValueError: Length mismatch”。在我制作的简单测试用例中,它总是 NAN 或单个结果,但没有窗口。

x = pd.DataFrame(x)
y = pd.DataFrame(y)

corr = y.rolling(np.shape(y)[0]).corr(x)
print(corr)
corr = y.rolling(np.shape(x)[0]).corr(x)
print(corr)
corr = x.rolling(np.shape(x)[0]).corr(y)
print(corr)
corr = x.rolling(np.shape(y)[0]).corr(y)
print(corr)
corr = y.rolling(np.shape(y)[0]).corr(x,pairwise=True)
print(corr)
corr = y.rolling(np.shape(x)[0]).corr(x,pairwise=True)
print(corr)
corr = x.rolling(np.shape(x)[0]).corr(y,pairwise=True)
print(corr)
corr = x.rolling(np.shape(y)[0]).corr(y,pairwise=True)
print(corr)

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    Rolling.applynp.corrcoefSeries.corry 等相同的索引值一起使用-因此Series.reset_indexdrop=True 是必要的:

    x= [0,1,2,3,4,5,4,7,6,9,10,5,6,4,8,7]
    y= [4,5,4,5]
    
    corrs = []
    for i in range(0,len(x)-3):
        corrs.append( np.corrcoef(x[i:i+4],y)[0,1] )
    
    x = pd.Series(x)
    y = pd.Series(y)
    
    corr1 = x.rolling(np.shape(y)[0]).apply(lambda x: np.corrcoef(x, y)[0,1], raw=True)
    corr2 = x.rolling(np.shape(y)[0]).apply(lambda x: x.reset_index(drop=True).corr(y), raw=False)
    

    print (pd.concat([pd.Series(corrs).rename(lambda x: x + 3), corr1, corr2], axis=1))
               0         1         2
    0        NaN       NaN       NaN
    1        NaN       NaN       NaN
    2        NaN       NaN       NaN
    3   0.447214  0.447214  0.447214
    4   0.447214  0.447214  0.447214
    5   0.447214  0.447214  0.447214
    6   0.000000  0.000000  0.000000
    7   0.816497  0.816497  0.816497
    8  -0.447214 -0.447214 -0.447214
    9   0.832050  0.832050  0.832050
    10  0.000000  0.000000  0.000000
    11 -0.242536 -0.242536 -0.242536
    12  0.242536  0.242536  0.242536
    13 -0.768350 -0.768350 -0.768350
    14  0.845154  0.845154  0.845154
    15 -0.507093 -0.507093 -0.507093
    

    【讨论】:

    • corr1 示例给出所有输入数组维度必须完全匹配的错误
    • @user-2147482637 - 你测试x = pd.Series(x) y = pd.Series(y) 吗?
    • 我明白了,是的,这是个问题,它不适用于数据帧
    • 我发现我可以将 x 保留为数据框,并在 apply 方法中执行 y.T 并且它可以工作
    • 即使数据大小相同,滚动窗口也不起作用,例如用 0 填充其余部分。在 numpy 上使用带有此滚动窗口的 apply 实在是太慢了。
    猜你喜欢
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 2015-01-28
    • 2019-04-26
    • 2020-08-02
    • 2021-08-20
    相关资源
    最近更新 更多