利用PYTHON计算偏相关系数(Partial correlation coefficient)
在统计学中,我们经常使用皮尔逊相关系数来衡量两个变量之间的线性关系。然而,有时我们感兴趣的是理解两个变量之间的关系,同时控制第三个变量。
例如,假设我们想要测量学生学习的小时数和他们获得的期末考试成绩之间的关联,同时控制学生在班级中的当前成绩。在这种情况下,我们可以使用部分相关来衡量学习时间和期末考试成绩之间的关系。
例如:Partial Correlation in Python
假设我们有如下的DataFrame,它显示了10名学生的当前年级、学习总小时数和期末考试成绩:
为了在控制currentGrade的同时计算hours和examScore之间的部分相关性,我们可以使用pingouin包中的partial_corr()函数,它使用以下语法:
partial_corr(data, x, y, covar)
where:
data: name of the dataframe
x, y: names of columns in the dataframe
covar: the name of the covariate column in the dataframe (e.g. the variable you’re controlling for)
#install and import pingouin package
pip install pingouin
import pingouin as pg
#find partial correlation between hours and exam score while controlling for grade
pg.partial_corr(data=df, x='hours', y='examScore', covar='currentGrade')
n r CI95% r2 adj_r2 p-val BF10 power
pearson 10 0.191 [-0.5, 0.73] 0.036 -0.238 0.598 0.438 0.082
我们可以看到,学习时数与期末考试成绩的偏相关系数为0.191,是一个很小的正相关。随着学习时间的增加。如果当前的分数保持不变,考试分数也会增加。
要一次性计算多个变量之间的部分相关性,可以使用.pcorr()函数:
#calculate all pairwise partial correlations, rounded to three decimal places
df.pcorr().round(3)
currentGrade hours examScore
currentGrade 1.000 -0.311 0.736
hours -0.311 1.000 0.191
examScore 0.736 0.191 1.000
翻译于https://www.statology.org/partial-correlation-python/