python - 两个数据帧的所有列对之间的列相关性
问题描述
嗨,所以我创建了一个函数来检查 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
```
解决方案
我会避免使用两个 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
推荐阅读
- r - 注销密码闪亮的应用程序
- jquery - 如何将段落的值传递给控制器
- magento - Magento2 缺货相关产品未显示在可配置产品的下拉选项中
- python - 比较多个文本文件,并保存公用值
- apache2 - 如何解决 modsec_audit.log 错误
- google-apps-script - 在 Google 应用程序脚本(Google Drive API / REST V2)中调用 Drive.Files.get(fileId,{alt: 'media'}) 时出错
- c# - 如何将文本从一种形式同步到另一种形式?
- visual-studio-2017 - VS2017打开.sln会自动打开相同的文件
- database - 如何在 postgresql 中镜像整个数据库集群
- javascript - .then 链接不起作用。为什么?