How to Perform Fisher’s Exact Test in Python


Fisher's exact test is a statistical test used to determine if there is a significant association between two categorical variables. It is commonly used in medical research, genetics, and other fields where small sample sizes are common. In Python, we can perform Fisher's exact test using the scipy.stats module.

Here's an example of how to perform Fisher's exact test in Python:

from scipy.stats import fisher_exact

# create a contingency table
table = [[10, 5], [3, 8]]

# perform Fisher's exact test
odds_ratio, p_value = fisher_exact(table)

print("Odds ratio:", odds_ratio)
print("p-value:", p_value)

In this example, we first create a contingency table with two rows and two columns. The rows represent the two categories we are interested in, and the columns represent the two possible outcomes for each category. We then pass this table to the fisher_exact function, which returns the odds ratio and p-value for the test.

Another way to perform Fisher's exact test in Python is to use the statsmodels module. Here's an example:

import statsmodels.api as sm

# create a contingency table
table = [[10, 5], [3, 8]]

# perform Fisher's exact test
result = sm.stats.Table2x2(table).fisher_exact()

print("Odds ratio:", result[0])
print("p-value:", result[1])

In this example, we first import the statsmodels module and create a contingency table. We then pass this table to the Table2x2 function, which creates a 2x2 contingency table object. We can then call the fisher_exact method on this object to perform the test and get the odds ratio and p-value.

Both of these methods will give you the same results for Fisher's exact test.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.