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

查看:261
本文介绍了等效于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

首先获取相关值(皮尔逊氏)

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%区间概率密度函数,并应用two-sided条件公式

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天全站免登陆