首页 > 解决方案 > 两个数据帧的所有列对之间的列相关性

问题描述

嗨,所以我创建了一个函数来检查 2 个变量之间的相关性,有人知道如何从中创建一个新的数据框吗?

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
```

标签: pythonpandasnumpydataframe

解决方案


我会避免使用两个 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


推荐阅读