Question

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.

Was it helpful?

Solution

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

> qchisq(0.05,5)
[1] 1.145476

in Python:

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top