Numpy/Pandas 关联 2 个不同长度的数组

rev*_*dar 2 python math numpy pattern-matching pearson-correlation

我正在尝试计算 2 个长度不同的数据集的相关系数。以下代码仅适用于等长数组。

import numpy as np
from scipy.stats.stats import pearsonr

a = [0, 0.4, 0.2, 0.4, 0.2, 0.4, 0.2, 0.5]
b = [25, 40, 62, 58, 53, 54]

print pearsonr(a, b)
Run Code Online (Sandbox Code Playgroud)

在我的情况下,b矢量长度可以在 50 - 100 个数据点之间变化。虽然我想要匹配的功能是标准的。附上的图片a。是否有其他首选模块可以匹配此类模式?

在此处输入图片说明

np8*_*np8 5

聚会有点晚了,但由于这是谷歌的最高结果,我会为这个问题提供一个可能的答案:

import pandas as pd
from scipy.stats import pearsonr 
import numpy as np 


a = [ 0, 0.4, 0.2, 0.4, 0.2, 0.45, 0.2, 0.52, 0.52, 0.4, 0.21, 0.2, 0.4, 0.51]
b = [ 0.4, 0.2, 0.5]


df = pd.DataFrame(dict(x=a))

CORR_VALS = np.array(b)
def get_correlation(vals):
    return pearsonr(vals, CORR_VALS)[0]

df['correlation'] = df.rolling(window=len(CORR_VALS)).apply(get_correlation)

Run Code Online (Sandbox Code Playgroud)

解释

pandasDataFrames 具有rolling()将数组长度 length ( window) 作为参数的方法。从返回的对象rolling()具有apply()将函数作为参数的方法。例如,您可以使用scipy.stats 中的 pearsonr计算Pearson 相关系数

示例输出

In [2]: df['correlation'].values
Out[2]:
array([        nan,         nan, -0.65465367,  0.94491118, -0.94491118,
        0.98974332, -0.94491118,  0.9923356 , -0.18898224, -0.75592895,
       -0.44673396,  0.1452278 ,  0.78423011,  0.16661846])
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

使用问题中的示例数据

In [1]: df
Out[1]:
     x  correlation
0  0.0          NaN
1  0.4          NaN
2  0.2          NaN
3  0.4          NaN
4  0.2          NaN
5  0.4     0.527932
6  0.2    -0.159167
7  0.5     0.189482
Run Code Online (Sandbox Code Playgroud)