Pandas - 两个没有对齐的数据帧之间的相关性

Pandas - Correlation between two dataframes without alignment

我需要获取两个数据帧列之间的相关性。它们都有相同的列,但可能由于对齐而导致相关性不起作用。

我不太关心数据帧的索引,我只是不想关联单元格中的值,将每一列视为随机分布。

我不确定是我的 pandas 还是我的数学技能欠缺,但我不明白在这种情况下对齐的目的是什么。

这是我的代码:

def correlation(indv1, indv2):
    frame1 = pd.DataFrame(indv1).select_dtypes(include=['float64', 'int64']) # Filtra o individuo para ficar apenas com valores int ou float
    frame2 = pd.DataFrame(indv2).select_dtypes(include=['float64', 'int64'])
    result = frame1.corrwith(frame2)
    return result.sum()

这是我试过的:

这是一个出错的例子:

test1 = pd.Series(np.random.random(3), index=[0, 1, 2])
test2 = pd.Series(np.random.random(3), index=[3, 4, 5])
print(correlation(test1, test2))

如果打印相关函数的结果数组,它显示 NaN。

这是我想要做的(每列):

X 是来自单元格的值,mi 和 sigma 是平均值和标准差。开发者列的。

您忽略了求和的数学索引。那些是 (Xi - muX)(Yi - muY)。它们的对齐方式绝对重要。

如果您不关心对齐索引但想关联它们现有的顺序并且您知道长度相同,请试试这个:

def correlation(indv1, indv2):
    frame1 = pd.DataFrame(indv1).select_dtypes(include=['float64', 'int64']) # Filtra o individuo para ficar apenas com valores int ou float
    frame2 = pd.DataFrame(indv2).select_dtypes(include=['float64', 'int64'])
    # Part I changed                /--------------------\
    result = frame1.corrwith(frame2.set_index(frame1.index))
    return result.sum()

演示

np.random.seed([3, 1415])
test1 = pd.Series(np.random.random(3), index=[0, 1, 2])
test2 = pd.Series(np.random.random(3), index=[3, 4, 5])
print(correlation(test1, test2))

-0.719774418655