本文目录导读:

我来详细介绍如何使用Pandas进行数据相关性分析:
基础相关性计算
导入库和创建示例数据
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 创建示例数据
data = {
'年龄': [25, 30, 35, 40, 45, 50, 55, 60],
'收入': [30000, 45000, 55000, 60000, 65000, 70000, 75000, 80000],
'支出': [20000, 28000, 35000, 38000, 40000, 42000, 45000, 48000],
'工作年限': [1, 3, 5, 8, 12, 15, 18, 20]
}
df = pd.DataFrame(data)
print(df)
计算相关系数矩阵
# 计算所有数值列之间的相关系数
correlation_matrix = df.corr()
print("相关系数矩阵:")
print(correlation_matrix)
# 选择特定方法:pearson(默认)、spearman、kendall
pearson_corr = df.corr(method='pearson')
spearman_corr = df.corr(method='spearman')
kendall_corr = df.corr(method='kendall')
可视化相关系数
热力图展示相关性
import seaborn as sns
# 方法1:使用seaborn热力图
plt.figure(figsize=(10, 8))
sns.heatmap(correlation_matrix,
annot=True, # 显示数值
cmap='coolwarm', # 颜色映射
center=0, # 中心值
square=True,
linewidths=1,
fmt='.2f')'相关性热力图')
plt.show()
散点图矩阵
# 显示变量间的散点图关系 sns.pairplot(df) plt.show()
实际应用案例
案例1:股票数据相关性分析
# 模拟股票数据
stock_data = pd.DataFrame({
'日期': pd.date_range('2023-01-01', periods=100, freq='D'),
'股票A': np.random.randn(100).cumsum() + 100,
'股票B': np.random.randn(100).cumsum() + 100,
'股票C': np.random.randn(100).cumsum() + 100
})
# 计算每日收益率
returns_data = stock_data[['股票A', '股票B', '股票C']].pct_change().dropna()
# 计算收益率相关性
returns_corr = returns_data.corr()
print("股票收益率相关性:")
print(returns_corr)
案例2:销售数据相关性分析
# 创建销售数据
sales_data = pd.DataFrame({
'广告支出': [1000, 1500, 2000, 2500, 3000, 3500, 4000],
'销售额': [10000, 15000, 18000, 22000, 28000, 32000, 38000],
'客户数量': [50, 75, 90, 110, 140, 160, 190],
'销售人员数': [5, 5, 6, 6, 7, 7, 8]
})
# 分析广告支出与销售额的关系
sales_corr = sales_data['广告支出'].corr(sales_data['销售额'])
print(f"广告支出与销售额的相关系数:{sales_corr:.2f}")
# 完整相关性分析
complete_corr = sales_data.corr()
print("\n完整相关性矩阵:")
print(complete_corr)
高级相关性分析
部分相关性分析
# 分析两个变量在控制第三个变量下的相关性
from scipy import stats
def partial_corr(x, y, z):
"""计算部分相关系数"""
# 控制变量z,计算x和y的相关性
rx_z = stats.pearsonr(x, z)[0]
ry_z = stats.pearsonr(y, z)[0]
rxy = stats.pearsonr(x, y)[0]
# 使用公式计算部分相关系数
r_xy_z = (rxy - rx_z * ry_z) / (np.sqrt(1 - rx_z**2) * np.sqrt(1 - ry_z**2))
return r_xy_z
# 应用示例
x = sales_data['广告支出']
y = sales_data['销售额']
z = sales_data['客户数量']
partial_r = partial_corr(x, y, z)
print(f"控制客户数量后,广告支出与销售额的部分相关系数:{partial_r:.2f}")
时间序列相关性
# 滞后相关性分析
def lag_correlation(series1, series2, max_lag=5):
"""计算不同滞后期的相关性"""
correlations = {}
for lag in range(-max_lag, max_lag + 1):
if lag < 0:
corr = series1.shift(-lag).corr(series2)
elif lag > 0:
corr = series1.corr(series2.shift(lag))
else:
corr = series1.corr(series2)
correlations[lag] = corr
return correlations
# 示例
np.random.seed(42)
time_series1 = pd.Series(np.random.randn(100).cumsum())
time_series2 = time_series1.shift(3) + np.random.randn(100) * 0.5
lag_corrs = lag_correlation(time_series1.dropna(), time_series2.dropna())
print("滞后相关性:")
for lag, corr in lag_corrs.items():
print(f"滞后{lag}期: {corr:.3f}")
相关性分析的最佳实践
class CorrelationAnalyzer:
def __init__(self, dataframe):
self.df = dataframe
def analyze_correlations(self, threshold=0.7):
"""分析相关性,找出强相关对"""
corr_matrix = self.df.corr()
# 找出强相关对
strong_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]) >= threshold:
strong_corr.append({
'var1': corr_matrix.columns[i],
'var2': corr_matrix.columns[j],
'correlation': corr_matrix.iloc[i, j]
})
return pd.DataFrame(strong_corr)
def check_multicollinearity(self, threshold=0.8):
"""检查多重共线性"""
corr_matrix = self.df.corr()
# 找出高度相关的变量对
collinear_pairs = []
columns = corr_matrix.columns
for i in range(len(columns)):
for j in range(i+1, len(columns)):
if abs(corr_matrix.iloc[i, j]) > threshold:
collinear_pairs.append((columns[i], columns[j], corr_matrix.iloc[i, j]))
return collinear_pairs
# 使用示例
analyzer = CorrelationAnalyzer(df)
strong_correlations = analyzer.analyze_correlations(threshold=0.6)
print("强相关对:")
print(strong_correlations)
collinear_vars = analyzer.check_multicollinearity()
print("\n多重共线性检查:")
for var1, var2, corr in collinear_vars:
print(f"{var1} 和 {var2} 相关性: {corr:.2f}")
注意事项和建议
# 1. 数据标准化
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
df_scaled = pd.DataFrame(
scaler.fit_transform(df.select_dtypes(include=[np.number])),
columns=df.select_dtypes(include=[np.number]).columns
)
# 2. 处理缺失值
df_clean = df.dropna() # 删除缺失值
# 或
df_filled = df.fillna(df.mean()) # 用均值填充
# 3. 非参数检验
from scipy.stats import spearmanr, kendalltau
# 当数据不服从正态分布时使用
spearman_corr, p_value = spearmanr(df['年龄'], df['收入'])
print(f"Spearman相关系数: {spearman_corr:.3f}, p值: {p_value:.3f}")
# 4. 显著性检验
from scipy import stats
def correlation_significance(x, y):
"""计算相关系数及其显著性"""
r, p_value = stats.pearsonr(x, y)
return {
'相关系数': r,
'p值': p_value,
'显著性': '显著' if p_value < 0.05 else '不显著'
}
result = correlation_significance(df['年龄'], df['收入'])
print(f"相关性显著性检验: {result}")
这些示例涵盖了Pandas相关性分析的主要方面。
- Pearson相关系数适用于线性关系
- Spearman适用于单调关系
- 相关性不代表因果关系
- 需要注意异常值的影响
- 可视化对于理解相关性很重要