numpy中的 np.corrcoef(x,y)
numpy.corrcoef(x, y=None, rowvar=True, bias=<no value>, ddof=<no value>, *, dtype=None)
返回的是相关系数矩阵。
x = np.random.normal(0, 1, 500)
y_low_noise = x + np.random.normal(0, 1, 500)
y_high_noise = x + np.random.normal(0, 10, 500)
print(np.corrcoef(x, y_low_noise))
print(np.corrcoef(x, y_high_noise))
[[1. 0.71462367]
[0.71462367 1. ]]
[[1. 0.14484914]
[0.14484914 1. ]]
scipy.stats中的pearsonr(x,y)
scipy.stats.pearsonr(x, y, *, alternative='two-sided')
返回的是(相关系数,p值)
print('low noise:', stats.pearsonr(x, y_low_noise))
print('high noise:', stats.pearsonr(x, y_high_noise))
low noise: (0.7146236707357696, 2.5427607603171753e-79)
high noise: (0.14484913606344066, 0.0011623421386268058)
pandas中的corr()
输入一个dataframe矩阵,计算每一列间的相关系数。返回相关系数的矩阵(dataframe)。