皮尔逊相关系数
用numpy实现
import numpy as npx = np.array([1, 4, 3, 5])
y = np.array([1, 3, 4, 5])
pc = np.corrcoef(x, y)print(pc)
输出结果:
调用scipy.stats中的pearsonr方法
from scipy.stats import pearsonr
import numpy as npx = np.array([1, 4, 3, 5])
y = np.array([1, 3, 4, 5])pc = pearsonr(x, y)print("相关系数:", pc[0])
print("显著性水平:", pc[1])
输出结果:
用pandas实现
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as pltdata = pd.DataFrame({"x": [1, 4, 3, 5], "y": [1, 3, 4, 5]})
df_corr = data.corr("pearson")
print(df_corr)# 画出热力图
sns.heatmap(df_corr, vmax=1, vmin=-1, center=0, annot=True)
plt.savefig('heatmap_corr_example.png')
输出结果: