【发布时间】:2018-09-04 18:55:23
【问题描述】:
我有两个形状相同的矩阵:
import numpy as np
from scipy.stats import pearsonr
np.random.seed(10)
a = np.random.random(30).reshape(10,3)
b = np.random.random(30).reshape(10,3)
即 10 行和 3 列。我需要每个矩阵中具有相同列索引的列的 滚动 相关性。慢的方法是:
def roll_corr((a, b), window):
out = np.ones_like(a)*np.nan
for i in xrange(window-1, a.shape[0]):
#print "%d --> %d" % ((i-(window-1)), i)
for j in xrange(a.shape[1]):
out[i, j] = pearsonr(
a[(i-(window-1)):(i), j], b[(i-(window-1)):(i), j]
)[0]
return out
roll_corr((a, b), 5) 的结果如我所愿,
array([[ nan, nan, nan],
[ nan, nan, nan],
[ nan, nan, nan],
[ nan, nan, nan],
[ 0.28810753, 0.27836622, 0.88397851],
[-0.04076151, 0.45254981, 0.83259104],
[ 0.62262963, -0.4188768 , 0.35479134],
[ 0.13130652, -0.91441413, -0.21713372],
[ 0.54327228, -0.91390053, -0.84033286],
[ 0.45268257, -0.95245888, -0.50107515]])
问题是:有没有更惯用的 numpy 方法来做到这一点?矢量化?跨步技巧?麻木?
我已经搜索过但没有找到这个。我不想使用熊猫;必须是 numpy。
【问题讨论】:
-
发布的任何一种解决方案都适合您吗?