将静态函数转换为滚动函数

时间:2019-05-04 15:31:28

标签: python pandas

我有一个可以正常工作的静态功能。我想在滚动功能中使用该功能。例如,我计算了过去21天中两个变量(x,y)的距离相关性。我的解决方案是正确的,但我想在过去100天内运行滚动距离关联,以在图表上直观地看到它。通过添加几行简单的python代码,关于如何将静态函数转换为动态函数的想法?

X = df.to_records(index=False)
Y = df1.to_records(index=False)

def distcorr(X, Y):
    X = np.atleast_1d(X)
    Y = np.atleast_1d(Y)
    if np.prod(X.shape) == len(X):
        X = X[:, None]
    if np.prod(Y.shape) == len(Y):
        Y = Y[:, None]
    X = np.atleast_2d(X)
    Y = np.atleast_2d(Y)
    n = X.shape[0]
    if Y.shape[0] != X.shape[0]:
        raise ValueError('Number of samples must match')
    a = squareform(pdist(X))
    b = squareform(pdist(Y))
    A = a - a.mean(axis=0)[None, :] - a.mean(axis=1)[:, None] + a.mean()
    B = b - b.mean(axis=0)[None, :] - b.mean(axis=1)[:, None] + b.mean()

    dcov2_xy = (A * B).sum()/float(n * n)
    dcov2_xx = (A * A).sum()/float(n * n)
    dcov2_yy = (B * B).sum()/float(n * n)
    dcor = np.sqrt(dcov2_xy)/np.sqrt(np.sqrt(dcov2_xx) * np.sqrt(dcov2_yy))
    return dcor

0 个答案:

没有答案