Create contingency table for fisher's exact

Viewed 103

Consider this example dataframe:

d = {'Gender': [1,1,0,1,0], 'Employed': [1,0,0,1,1]}

Running the following fives me a contingency table

import statsmodels.api as sm
import pandas as pd

d=pd.DataFrame(d)
table = sm.stats.Table.from_data(d)

This gives me a contingency table in the form

A 2x2 contingency table with counts:
[[1. 1.]
[1. 2.]]

I would like to be able to put 'table' directly into the fisher exact function but this gives an error as the fisher exact function wants a table in this form:

stats.fisher_Exact[[1,1],[1,2]]

How can I automatically create a contingency table in the correct format so that I don't have to rewrite it out the correct way?

1 Answers

This works fine, but you had several typos:

d = {'Gender': [1,1,0,1,0], 'Employed': [1,0,0,1,1]}

import statsmodels.api as sm
import pandas as pd
d=pd.DataFrame(d)
table = sm.stats.Table.from_data(d)

from scipy import stats
oddsratio, pvalue = stats.fisher_exact(table.table)
print(oddsratio, pvalue)

output: 2.0 1.0

Related