📚 目录
- 相关性分析简介
- 计算相关系数
- 皮尔逊相关系数
- 斯皮尔曼等级相关系数
- 热力图可视化
- 参考资料
- 出站链接
1. 相关性分析简介
相关性分析用于揭示数据集中两个或多个变量之间的关系强度。Pandas 提供了几种计算相关性的方法,通常用于探索性数据分析(EDA)和特征选择。
2. 计算相关系数
在 Pandas 中,corr()
函数可以计算 DataFrame 中数值列之间的相关性。它使用不同的方法来度量变量之间的线性关系。
correlation_matrix = df.corr()
print(correlation_matrix)
3. 皮尔逊相关系数
皮尔逊相关系数是最常用的相关性度量,表示两个变量之间的线性关系。它的值范围从 -1 到 1,值为 1 时表示完全正相关,-1 时表示完全负相关,0 表示没有线性关系。
✅ 计算皮尔逊相关系数:
correlation = df['Age'].corr(df['Income'])
print(f"皮尔逊相关系数: {correlation}")
✅ 计算整个 DataFrame 的皮尔逊相关系数矩阵:
correlation_matrix = df.corr(method='pearson')
4. 斯皮尔曼等级相关系数
斯皮尔曼等级相关系数是用于衡量两个变量间的单调关系的非参数统计方法,适用于非线性关系。
✅ 计算斯皮尔曼等级相关系数:
correlation_spearman = df['Age'].corr(df['Income'], method='spearman')
print(f"斯皮尔曼相关系数: {correlation_spearman}")
✅ 计算整个 DataFrame 的斯皮尔曼相关系数矩阵:
correlation_matrix_spearman = df.corr(method='spearman')
5. 热力图可视化
使用热力图(Heatmap)可以有效地可视化相关性矩阵,帮助更直观地理解变量之间的相关性。
✅ 使用 Seaborn 绘制热力图:
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
sns.heatmap(df.corr(), annot=True, cmap='coolwarm', fmt='.2f', linewidths=0.5)
plt.title("Correlation Heatmap")
plt.show()
📖 参考资料
- 《Python for Data Analysis》第十章:相关性分析与数据可视化
- Real Python – Understanding Correlation in Python with Pandas
- Pandas 官方文档:DataFrame.corr() 方法
发表回复