大家好,我已经创建了一个函数来检查两个变量之间的相关性,有谁知道我如何从这个函数中创建一个新的数据框?
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')下面是相关函数的输出示例:
Out [1]:
Pearson Correlation (0.05, -0.1620045985125294)
banana and orange are not correlated
Pearson Correlation (0.05, 0.2267582070839226)
apple and orange are highly correlated发布于 2020-05-29 16:31:38
我会避免使用两个for循环。根据数据集的大小,这将非常慢。
Pandas提供了一个关联函数,这里可能会用到:
import pandas as pd
df = pd.DataFrame({'A': range(4), 'B': [2*i for i in range(4)]})使用corr()将给出成对的关联,然后返回,并返回一个新的数据帧
df.corr()有关更多信息,请查看手册:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.corr.html
发布于 2020-05-29 16:09:06
您可以只执行以下操作。
df = pd.DataFrame(index=X.columns, columns=Y.columns)
#In your loop
df[colY][colX] = corr然后,您的循环将是
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))
df[colY][colX] = 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')发布于 2020-05-29 17:37:19
我认为你正在寻找这个:这将获得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 Truehttps://stackoverflow.com/questions/62080994
复制相似问题