Python 两个数据帧的所有列对之间的列相关

Python 两个数据帧的所有列对之间的列相关,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,大家好,我创建了一个函数来检查两个变量之间的相关性,有人知道如何从中创建新的数据帧吗 In [1]:from scipy.stats import pearsonr for colY in Y.columns: for colX in X.columns: #print('Pearson Correlation') corr, _ = pearsonr(numerical_cols_target[colX], numerical_cols_target[colY]

大家好,我创建了一个函数来检查两个变量之间的相关性,有人知道如何从中创建新的数据帧吗

In [1]:from scipy.stats import pearsonr
for colY in Y.columns:
    for colX in X.columns:
    #print('Pearson Correlation')
        corr, _ = pearsonr(numerical_cols_target[colX], numerical_cols_target[colY])
        alpha = 0.05
        print('Pearson Correlation', (alpha, corr))
        if corr <= alpha:
            print(colX +' and ' +colY+ ' two ariables are not correlated ')
        else:
            print(colX +' and ' +colY+ ' two variables are highly correlated ')
        print('\n')
    print('\n')

您可以只做以下操作

df=pd.DataFrame(index=X.columns,columns=Y.columns)
#在你的圈子里
df[colY][colX]=corr
然后,您的循环将是

Y列中的colY的
:
对于X.columns中的colX:
#打印(‘皮尔逊相关’)
corr,uu=pearsonr(数值目标[colX],数值目标[colY])
α=0.05
打印(‘皮尔逊相关性’,(α,corr))
df[colY][colX]=corr

如果corr我将避免使用两个for循环。根据数据集的大小,这将非常缓慢

Pandas提供了一个相关函数,其中可能包含:

import pandas as pd

df = pd.DataFrame({'A': range(4), 'B': [2*i for i in range(4)]})
使用corr()将为您提供成对关联,然后并返回一个新的数据帧

df.corr()

有关更多信息,您可以查看手册:

我想您正在寻找: 这将获得X和Y数据帧之间每两对列的逐列关联,并创建另一个数据帧,以保持所有关联以及它们是否通过阈值alpha: 这假设Y的列数少于或等于X。如果不是简单地切换X和Y的位置:

import collections
corr_df = pd.DataFrame(columns=['col_X', 'col_Y', 'corr', 'is_correlated'])
d = collections.deque(X.columns)
Y_cols = Y.columns
alpha = 0.05
for i in range(len(d)):
  d.rotate(i)
  X = X[d]
  corr = Y.corrwith(X, axis=0)
  corr_df = corr_df.append(pd.DataFrame({'col_X':list(d)[:len(Y_cols)], 'col_Y':Y.columns, 'corr':corr[:len(Y_cols)], 'is_correlated':corr[:len(Y_cols)]>alpha}))
print(corr_df.reset_index())
输入和输出示例:

X:
   A  B   C
0  2  2  10
1  4  0   2
2  8  0   1
3  0  0   8

Y:
   B   C
0  2  10
1  0   2
2  0   1
3  0   8


correlation(X, Y):

  col_X col_Y  corr is_correlated
0     A     B   1.0          True
1     B     C   1.0          True
2     C     B   1.0          True
3     A     C   1.0          True
4     A     B   1.0          True
5     B     C   1.0          True

欢迎来到Stackoverflow。请花点时间阅读这篇文章,以及如何提供答案,并相应地修改你的问题。这些提示可能也很有用。
X:
   A  B   C
0  2  2  10
1  4  0   2
2  8  0   1
3  0  0   8

Y:
   B   C
0  2  10
1  0   2
2  0   1
3  0   8


correlation(X, Y):

  col_X col_Y  corr is_correlated
0     A     B   1.0          True
1     B     C   1.0          True
2     C     B   1.0          True
3     A     C   1.0          True
4     A     B   1.0          True
5     B     C   1.0          True