人工智能之数据分析 Pandas
第七章 相关性分析
文章目录
- [人工智能之数据分析 Pandas](#人工智能之数据分析 Pandas)
- 前言
- [📊 一、什么是相关性?](#📊 一、什么是相关性?)
- [🔢 二、常用相关系数类型](#🔢 二、常用相关系数类型)
- [🧮 三、Pandas 相关性计算详解](#🧮 三、Pandas 相关性计算详解)
- [1. 基础方法:`.corr()`](#1. 基础方法:
.corr())- [2. 计算两列之间的相关性](#2. 计算两列之间的相关性)
- [3. 处理缺失值](#3. 处理缺失值)
- [🎨 四、相关性可视化(关键!)](#🎨 四、相关性可视化(关键!))
- [1. 使用 Seaborn(推荐)](#1. 使用 Seaborn(推荐))
- [2. 使用 Matplotlib(纯 Pandas 风格)](#2. 使用 Matplotlib(纯 Pandas 风格))
- [3. 突出高相关对(实用技巧)](#3. 突出高相关对(实用技巧))
- [🔍 五、进阶分析技巧](#🔍 五、进阶分析技巧)
- [1. 分组相关性(Group-wise Correlation)](#1. 分组相关性(Group-wise Correlation))
- [2. 相关性与目标变量(Feature Relevance)](#2. 相关性与目标变量(Feature Relevance))
- [3. 偏相关(Partial Correlation)--- 需借助其他库](#3. 偏相关(Partial Correlation)— 需借助其他库)
- [⚠️ 六、注意事项与陷阱](#⚠️ 六、注意事项与陷阱)
- [📦 七、完整分析流程模板](#📦 七、完整分析流程模板)
- [✅ 总结](#✅ 总结)
- 后续
- 资料关注
前言
相关性分析(Correlation Analysis) 是探索变量之间线性或非线性关系的重要手段,广泛应用于特征选择、业务洞察、建模前分析等场景。Pandas 提供了简洁高效的工具来计算和可视化相关性。
本文将从 理论基础、Pandas 实现、可视化、进阶技巧 四个维度,系统、深入、实战化地介绍 Pandas 相关性分析的完整流程。
📊 一、什么是相关性?
相关性衡量两个变量之间的关联程度和方向:
- 正相关:一个变量增大,另一个也倾向于增大(如身高 vs 体重)
- 负相关:一个变量增大,另一个倾向于减小(如广告投入 vs 跳出率)
- 无相关:变量间无线性关系
⚠️ 注意:相关 ≠ 因果!高相关性不代表因果关系。
🔢 二、常用相关系数类型
| 类型 | 适用数据 | Pandas 方法 | 特点 |
|---|---|---|---|
| Pearson | 连续、线性、近似正态分布 | 'pearson'(默认) |
衡量线性相关强度 |
| Spearman | 连续/有序,单调关系 | 'spearman' |
基于秩次,对异常值鲁棒 |
| Kendall | 小样本、有序数据 | 'kendall' |
计算慢,但统计性质好 |
公式简述:
-
Pearson 相关系数:
r = ∑ ( x i − x ˉ ) ( y i − y ˉ ) ∑ ( x i − x ˉ ) 2 ∑ ( y i − y ˉ ) 2 r = \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum (x_i - \bar{x})^2 \sum (y_i - \bar{y})^2}} r=∑(xi−xˉ)2∑(yi−yˉ)2 ∑(xi−xˉ)(yi−yˉ)
取值范围:[-1, 1]
1:完全正相关0:无线性相关-1:完全负相关
🧮 三、Pandas 相关性计算详解
1. 基础方法:.corr()
python
import pandas as pd
import numpy as np
# 示例数据
df = pd.DataFrame({
'身高': [170, 175, 180, 165, 160],
'体重': [65, 70, 80, 60, 55],
'年龄': [25, 30, 35, 20, 18],
'收入': [8000, 9000, 12000, 7000, 6000]
})
# 计算所有数值列的 Pearson 相关矩阵
corr_matrix = df.corr(method='pearson')
print(corr_matrix)
输出示例:
身高 体重 年龄 收入
身高 1.000000 0.996195 0.960769 0.993399
体重 0.996195 1.000000 0.944911 0.997037
年龄 0.960769 0.944911 1.000000 0.981981
收入 0.993399 0.997037 0.981981 1.000000
参数说明:
| 参数 | 说明 |
|---|---|
method |
'pearson', 'spearman', 'kendall' |
min_periods |
计算相关性所需的最小非空观测数(用于缺失值处理) |
numeric_only |
是否仅包含数值列(pandas ≥ 2.0 默认为 True) |
2. 计算两列之间的相关性
python
# 方法1:用 corrwith(推荐)
df['身高'].corr(df['体重'], method='pearson')
# 方法2:从相关矩阵取值
df.corr().loc['身高', '体重']
3. 处理缺失值
python
# 自动忽略 NaN(pairwise deletion)
df_with_nan = df.copy()
df_with_nan.loc[0, '体重'] = np.nan
df_with_nan.corr() # 仍可计算,使用有效配对
✅ Pandas 的
.corr()默认采用 pairwise complete observations(成对删除),即只使用两个变量都非空的行。
🎨 四、相关性可视化(关键!)
数字矩阵不够直观,热力图(Heatmap) 是最佳展示方式。
1. 使用 Seaborn(推荐)
python
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
sns.heatmap(
corr_matrix,
annot=True, # 显示数值
cmap='coolwarm', # 颜色映射:红=正,蓝=负
center=0, # 以 0 为中心
square=True, # 方形单元格
fmt='.2f' # 保留两位小数
)
plt.title('变量相关性热力图')
plt.show()
2. 使用 Matplotlib(纯 Pandas 风格)
python
fig, ax = plt.subplots(figsize=(8, 6))
cax = ax.matshow(corr_matrix, cmap='coolwarm', vmin=-1, vmax=1)
fig.colorbar(cax)
ax.set_xticks(range(len(corr_matrix.columns)))
ax.set_yticks(range(len(corr_matrix.columns)))
ax.set_xticklabels(corr_matrix.columns, rotation=45)
ax.set_yticklabels(corr_matrix.columns)
plt.show()
3. 突出高相关对(实用技巧)
python
# 获取绝对值 > 0.7 的相关对(排除自相关)
high_corr = []
for i in range(len(corr_matrix.columns)):
for j in range(i+1, len(corr_matrix.columns)):
if abs(corr_matrix.iloc[i, j]) > 0.7:
high_corr.append((corr_matrix.columns[i],
corr_matrix.columns[j],
corr_matrix.iloc[i, j]))
print("高相关变量对:")
for pair in high_corr:
print(f"{pair[0]} ↔ {pair[1]}: {pair[2]:.3f}")
🔍 五、进阶分析技巧
1. 分组相关性(Group-wise Correlation)
分析不同子群体内的相关性是否一致:
python
# 按性别分组计算身高-体重相关性
df_full = pd.DataFrame({
'性别': ['男','男','女','女','男'],
'身高': [175,180,160,165,170],
'体重': [70,80,55,60,65]
})
def group_corr(group):
return group['身高'].corr(group['体重'])
df_full.groupby('性别').apply(group_corr)
# 输出:
# 性别
# 女 1.0
# 男 1.0
2. 相关性与目标变量(Feature Relevance)
在机器学习中,常计算各特征与目标变量的相关性:
python
# 假设 '收入' 是目标变量
target_corr = df.corr()['收入'].drop('收入').sort_values(key=abs, ascending=False)
print("特征与收入的相关性:")
print(target_corr)
3. 偏相关(Partial Correlation)--- 需借助其他库
Pandas 不直接支持偏相关(控制其他变量影响),但可用 pingouin 或 statsmodels:
python
# 示例(需安装 pingouin: pip install pingouin)
import pingouin as pg
pg.partial_corr(data=df, x='身高', y='收入', covar='年龄')
⚠️ 六、注意事项与陷阱
| 问题 | 说明 | 解决方案 |
|---|---|---|
| 非线性关系 | Pearson 无法捕捉曲线关系(如 U 型) | 先画散点图;尝试 Spearman 或多项式特征 |
| 异常值敏感 | 单个异常点可大幅扭曲 Pearson 系数 | 使用 Spearman;先清洗异常值 |
| 混杂变量 | 表面相关实为第三方变量导致 | 进行分组分析或偏相关 |
| 类别变量 | .corr() 忽略非数值列 |
对类别变量编码后分析(如 One-Hot) |
| 时间序列伪相关 | 两个趋势序列可能虚假高相关 | 先差分去趋势,再计算相关性 |
示例:非线性关系检测
python
# 生成非线性数据
x = np.linspace(-3, 3, 100)
y = x**2 + np.random.normal(0, 0.5, 100)
df_nl = pd.DataFrame({'x': x, 'y': y})
print("Pearson:", df_nl['x'].corr(df_nl['y'])) # ≈ 0(无线性相关)
print("Spearman:", df_nl['x'].corr(df_nl['y'], method='spearman')) # ≈ 0(非单调)
# 此时应看散点图!
plt.scatter(df_nl['x'], df_nl['y'])
📦 七、完整分析流程模板
python
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def analyze_correlation(df, target=None, method='pearson', threshold=0.7):
# 1. 仅保留数值列
numeric_df = df.select_dtypes(include=[np.number])
# 2. 计算相关矩阵
corr = numeric_df.corr(method=method)
# 3. 可视化
plt.figure(figsize=(10, 8))
sns.heatmap(corr, annot=True, cmap='coolwarm', center=0, fmt='.2f')
plt.title(f'{method.capitalize()} 相关性热力图')
plt.show()
# 4. 找出高相关对
high_pairs = []
for i in range(len(corr.columns)):
for j in range(i+1, len(corr.columns)):
if abs(corr.iloc[i, j]) >= threshold:
high_pairs.append((corr.columns[i], corr.columns[j], corr.iloc[i, j]))
if high_pairs:
print(f"\n高相关变量对(|r| ≥ {threshold}):")
for a, b, r in high_pairs:
print(f" {a} ↔ {b}: {r:.3f}")
# 5. 若指定目标变量,输出特征相关性排序
if target and target in corr.columns:
target_corr = corr[target].drop(target).sort_values(key=abs, ascending=False)
print(f"\n与 '{target}' 的相关性排序:")
print(target_corr)
return corr
# 使用
corr_result = analyze_correlation(df, target='收入', threshold=0.8)
✅ 总结
| 关键点 | 说明 |
|---|---|
.corr() 是核心 |
支持三种相关系数,自动处理缺失值 |
| 可视化必不可少 | 热力图让模式一目了然 |
| 先探索再下结论 | 结合散点图、业务知识判断相关性意义 |
| 警惕伪相关 | 时间序列、混杂变量、异常值都可能导致误导 |
| 相关性 ≠ 特征重要性 | 高相关特征也可能冗余,需结合模型验证 |
💡 下一步建议:
- 若用于机器学习,可结合
SelectKBest或VIF(方差膨胀因子)进行特征筛选- 对分类目标变量,使用 ANOVA F-value 或 互信息(Mutual Information)
后续
python过渡项目部分代码已经上传至gitee,后续会逐步更新。
资料关注
公众号:咚咚王
gitee:https://gitee.com/wy18585051844/ai_learning
《Python编程:从入门到实践》
《利用Python进行数据分析》
《算法导论中文第三版》
《概率论与数理统计(第四版) (盛骤) 》
《程序员的数学》
《线性代数应该这样学第3版》
《微积分和数学分析引论》
《(西瓜书)周志华-机器学习》
《TensorFlow机器学习实战指南》
《Sklearn与TensorFlow机器学习实用指南》
《模式识别(第四版)》
《深度学习 deep learning》伊恩·古德费洛著 花书
《Python深度学习第二版(中文版)【纯文本】 (登封大数据 (Francois Choliet)) (Z-Library)》
《深入浅出神经网络与深度学习+(迈克尔·尼尔森(Michael+Nielsen)》
《自然语言处理综论 第2版》
《Natural-Language-Processing-with-PyTorch》
《计算机视觉-算法与应用(中文版)》
《Learning OpenCV 4》
《AIGC:智能创作时代》杜雨+&+张孜铭
《AIGC原理与实践:零基础学大语言模型、扩散模型和多模态模型》
《从零构建大语言模型(中文版)》
《实战AI大模型》
《AI 3.0》