简体   繁体   中英

Is there a python equivalent of R's qchisq function?

The R qchisq function converts a p-value and number of degrees of freedom to the corresponding chi-squared value. Is there a Python library that has an equivalent?

I've looked around in SciPy without finding anything.

It's scipy.stats.chi2.ppf - Percent point function (inverse of cdf). Eg, in R:

> qchisq(0.05,5)
[1] 1.145476

in Python:

In [8]: scipy.stats.chi2.ppf(0.05, 5)
Out[8]: 1.1454762260617695

As @VadimKhotilovich points out in his answer, you can use scipy.stats.chi2.ppf . You can also use the function chdtri from scipy.special , but use 1-p as the argument.

R:

> qchisq(0.01, 7)
[1] 1.239042
> qchisq(0.05, 7)
[1] 2.16735

scipy:

In [16]: from scipy.special import chdtri

In [17]: chdtri(7, 1 - 0.01)
Out[17]: 1.2390423055679316

In [18]: chdtri(7, 1 - 0.05)
Out[18]: 2.1673499092980579

The only advantage to use chdtri over scipy.stats.chi2.ppf is that it is much faster:

In [30]: from scipy.stats import chi2

In [31]: %timeit chi2.ppf(0.05, 7)
10000 loops, best of 3: 135 us per loop

In [32]: %timeit chdtri(7, 1 - 0.05)
100000 loops, best of 3: 3.67 us per loop

Also in R

qchisq(0.05, 9, lower.tail=FALSE )

in Python would be

chi2.ppf(q= 0.95, df = 9) #q = (1-0.05)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM