How can I perform Fisher’s Exact Test in Python?

Fisher’s Exact Test is a statistical method used to analyze the significance of the association between two categorical variables. In Python, this test can be performed by using the “scipy.stats.fisher_exact” function from the SciPy library. This function takes in a contingency table as input and returns the probability of obtaining the observed data under the assumption of independence between the two variables. By comparing this probability to a chosen significance level, the test can determine whether there is a significant relationship between the two variables. This can be useful in various fields such as medicine, genetics, and social sciences where the analysis of categorical data is common.

Perform Fisher’s Exact Test in Python


 is used to determine whether or not there is a significant association between two categorical variables.

It is typically used as an alternative to the  when one or more of the cell counts in a 2×2 table is less than 5. 

This tutorial explains how to perform Fisher’s Exact Test in Python.

Example: Fisher’s Exact Test in Python

Suppose we want to know whether or not gender is associated with political party preference at a particular college.

To explore this, we randomly poll 25 students on campus. The number of students who are Democrats or Republicans, based on gender, is shown in the table below:

  Democrat Republican
Female 8 4
Male 4 9

To determine if there is a statistically significant association between gender and political party preference, we can use the following steps to perform Fisher’s Exact Test in Python:

Step 1: Create the data.

First, we will create a table to hold our data:

data = [[8, 4],
         [4, 9]]

Step 2: Perform Fisher’s Exact Test.

Next, we can perform Fisher’s Exact Test using the  from the SciPy library, which uses the following syntax:

fisher_exact(table, alternative=’two-sided’) 

where:

  • table: A 2×2 contingency table
  • alternative: Defines the alternative hypothesis. Default is ‘two-sided’, but you can also choose ‘less’ or ‘greater’ for one-sided tests.

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

import scipy.stats as stats

print(stats.fisher_exact(data))

(4.5, 0.1152)

The p-value for the tests is 0.1152.

Fisher’s Exact Test uses the following null and alternative hypotheses:

  • H0: (null hypothesis) The two variables are independent.
  • H1: (alternative hypothesis) The two variables are not independent.

Since this p-value is not less than 0.05, we do not reject the null hypothesis.

Thus, we don’t have sufficient evidence to say that there is a significant association between gender and political party preference.

In other words, gender and political party preference are independent.

x