Python implements Pearson correlation test

Python implements Pearson correlation test

The Pearson correlation test is a commonly used statistical method to examine the strength and direction of a linear relationship between two variables. In Python, the Pearson correlation test can be conveniently performed by the pearsonr function in the scipy library.

Below is an example showing how to use the pearsonr function in Python to calculate the correlation coefficient and p-value between two variables.

from scipy.stats import pearsonr

# 数据准备
x = [1, 2, 3, 4, 5]
y = [6, 7, 8, 9, 10]

# 计算相关系数和p值
corr, p_value = pearsonr(x, y)
print("相关系数:", corr)
print("p值:", p_value)

Run the above code, the output is as follows:

相关系数: 1.0
p值: 0.0

It can be seen from the results that there is a completely positive correlation between the two variables x and y, and the p value is 0, indicating that the significance of this relationship is very high.

Next, let's give a set of unrelated data to see the calculation results:

# 数据准备
x = [1, 2, 3, 4, 5]
y = [10, 9, 8, 7, 6]

# 计算相关系数和p值
corr, p_value = pearsonr(x, y)
print("相关系数:", corr)
print("p值:", p_value)

Run the above code, the output is as follows:

Guess you like

Origin blog.csdn.net/update7/article/details/131485727