Python 中 cor.test 的 R 等价物 [英] Equivalent of R's of cor.test in Python

查看:31
本文介绍了Python 中 cor.test 的 R 等价物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Python 中找到 r 置信区间?

Is there a way I can find the r confidence interval in Python?

在 R 中,我可以执行以下操作:

In R i could do something like:

cor.test(m, h)

    Pearson's product-moment correlation

data:  m and h
t = 0.8974, df = 4, p-value = 0.4202
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.6022868  0.9164582
sample estimates:
      cor 
0.4093729

在 Python 中,我可以使用以下方法计算 r (cor):

In Python I can calculate r (cor) using:

r,p = scipy.stats.pearsonr(df.age, df.pets)

但这不会返回 r 置信区间.

But that doesn't return the r confidence interval.

推荐答案

这是计算内部置信度的一种方法

Here's one way to calculate confidence internal

首先得到相关值(pearson's)

First get the correlation value (pearson's)

In [85]: from scipy import stats

In [86]: corr = stats.pearsonr(df['col1'], df['col2'])

In [87]: corr
Out[87]: (0.551178607008175, 0.0)

使用Fisher变换得到z

Use the Fisher transformation to get z

In [88]: z = np.arctanh(corr[0])

In [89]: z
Out[89]: 0.62007264620685021

还有,sigma 值,即标准误差

And, the sigma value i.e standard error

In [90]: sigma = (1/((len(df.index)-3)**0.5))

In [91]: sigma
Out[91]: 0.013840913308956662

得到正态连续随机变量的正态95%区间概率密度函数应用双边条件公式

Get normal 95% interval probability density function for normal continuous random variable apply two-sided conditional formula

In [92]: cint = z + np.array([-1, 1]) * sigma * stats.norm.ppf((1+0.95)/2)

最后取双曲正切得到 95% 的区间值

Finally take hyperbolic tangent to get interval values for 95%

In [93]: np.tanh(cint)
Out[93]: array([ 0.53201034,  0.56978224])

这篇关于Python 中 cor.test 的 R 等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆