10

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.

jveldridge
  • 1,155
  • 3
  • 11
  • 21
  • @mnel: That question relates to calculating the p-value from the chi squared value. I'm trying to go in the other direction. – jveldridge Aug 06 '13 at 01:23
  • indeed. Close-vote retracted (should read more carefully!) – mnel Aug 06 '13 at 01:31
  • http://stackoverflow.com/questions/11725115/p-value-from-chi-sq-test-statistic-in-python – IRTFM Aug 06 '13 at 01:53
  • @Dwin: That question relates to calculating the p-value from the chi squared value. I'm trying to go in the other direction. – jveldridge Aug 06 '13 at 01:54

3 Answers3

22

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
3

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
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
0

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)