10.7 C
London
Sunday, July 7, 2024
HomePythonChi-Square Tests in PythonHow to Perform Fisher’s Exact Test in Python

How to Perform Fisher’s Exact Test in Python

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Fisher’s Exact Test 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 Chi-Square Test of Independence 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 fisher_exact function 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.

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories