Home Â» How to Perform a Chi-Square Goodness of Fit Test in Python

# How to Perform a Chi-Square Goodness of Fit Test in Python

AÂ Chi-Square Goodness of Fit TestÂ is used to determineÂ whether or not a categorical variable follows a hypothesized distribution.

This tutorial explains how to perform a Chi-Square Goodness of Fit TestÂ in Python.

### Example: Chi-Square Goodness of Fit Test in Python

A shop owner claims that an equal number of customers come into his shop each weekday. To test this hypothesis, a researcher records the number of customers that come into the shop in a given week and finds the following:

• Monday:Â 50 customers
• Tuesday:Â 60 customers
• Wednesday:Â 40 customers
• Thursday:Â 47Â customers
• Friday:Â 53 customers

Use the following steps to perform a Chi-Square goodness of fit test in Python to determine if the data is consistent with the shop ownerâ€™s claim.

Step 1: Create the data.

First, we will create two arrays to hold our observed and expected number of customers for each day:

```expected = [50, 50, 50, 50, 50]
observed = [50, 60, 40, 47, 53]
```

Step 2: Perform the Chi-Square Goodness of Fit Test.

Next, we can perform the Chi-Square Goodness of Fit Test using the chisquare function from the SciPy library, which uses the following syntax:

chisquare(f_obs, f_exp)Â

where:

• f_obs:Â An array of observed counts.
• f_exp:Â An array of expected counts. By default, each category is assumed to be equally likely.

The following code shows how to use this function in our specific example:

```import scipy.stats as stats

#perform Chi-Square Goodness of Fit Test
stats.chisquare(f_obs=observed, f_exp=expected)

(statistic=4.36, pvalue=0.35947)
```

TheÂ Chi-Square test statistic is found to be 4.36Â and the corresponding p-value isÂ 0.35947.

Note that the p-value corresponds to a Chi-Square value with n-1 degrees of freedom (dof), where n is the number of different categories. In this case, dof = 5-1 = 4. You can use theÂ Chi-Square to P Value CalculatorÂ to confirm that the p-value that corresponds to X2 = 4.36 with dof = 4 isÂ 0.35947.

Recall that a Chi-Square Goodness of Fit Test uses the following null and alternative hypotheses:

• H0: (null hypothesis)Â A variable follows a hypothesized distribution.
• H1: (alternative hypothesis)Â A variable does not follow a hypothesized distribution.

Since the p-value (.35947) is not less than 0.05, we fail to reject the null hypothesis. This means we do not have sufficient evidence to say that the true distribution of customers is different from the distribution that the shop owner claimed.