Skip to content

Search Broadly Epi

Python · Epidemiologic Calculations

How to calculate an odds ratio in Python

Build a 2x2 contingency table in Python, calculate an odds ratio and 95% confidence interval by hand, and confirm the result with scipy.stats.fisher_exact. Uses a self-contained fictional case-control study with no external files required.

Outcome

What you will produce

Calculate an odds ratio and 95% confidence interval from a 2x2 contingency table in Python and interpret the result correctly.

Before you begin

  • Python 3.10 or later
  • NumPy and SciPy installed
  • Familiarity with 2x2 tables and the odds ratio concept

The study scenario

A fictional case-control study examined whether outdoor occupational sun exposure was associated with melanoma. Cases were 100 people recently diagnosed with melanoma. Controls were 100 people with no history of skin cancer, frequency-matched to cases by age and sex. Each person was classified as either predominantly outdoor (exposed) or predominantly indoor (unexposed) in their primary occupation.

Exposed (outdoor work) Unexposed (indoor work) Total
Cases (melanoma)80 (cell a)20 (cell b)100
Controls (no melanoma)40 (cell c)60 (cell d)100
Total12080200
Fictional 2×2 contingency table used throughout this tutorial. Cell labels a, b, c, d match the formula below.

Of the 100 cases, 80 were in outdoor occupations and 20 were not. Of the 100 controls, 40 were in outdoor occupations and 60 were not. The exposure rate is higher among cases than controls. The odds ratio will quantify how much higher.

Step 1: Build the table in Python

Represent the 2×2 table as a NumPy array. Name the four cells a, b, c, and d to match the formula you will use in the next step.

Code example temporarily unavailable: the previous gist did not match this odds-ratio lesson.

Running this prints the four cell values as a check before any calculations. Inspecting cell counts before computing a statistic is a habit worth keeping: transposed rows or swapped columns are a common source of wrong results in contingency-table work.

Step 2: Calculate the odds ratio and confidence interval

The odds ratio compares the odds of exposure among cases to the odds of exposure among controls. The formula using the cell labels from the table is:

Odds ratio formula

OR=a × db × c

Where a = cases exposed, b = cases unexposed, c = controls exposed, d = controls unexposed.

For this table: OR = (80 × 60) ÷ (20 × 40) = 4,800 ÷ 800 = 6.0. The confidence interval uses the natural log of the odds ratio and a standard-error formula based on the four cell counts.

Code example temporarily unavailable: the previous gist did not match this odds-ratio lesson.

Step 3: Cross-check with Fisher's exact test

Fisher’s exact test computes the odds ratio and a p-value without relying on large-sample approximations. It is preferable to the chi-squared test when any cell count is small. For this table the cells are large, so both approaches give similar results.

Code example temporarily unavailable: the previous gist did not match this odds-ratio lesson.

The two methods agree on the odds ratio of 6.0. fisher_exact also returns a p-value, which can be printed or stored for reporting.

Expected output

Cell a (cases, exposed):      80
Cell b (cases, unexposed):    20
Cell c (controls, exposed):   40
Cell d (controls, unexposed): 60

Odds ratio (manual): 6.00
95% CI: (3.19, 11.30)

Odds ratio (Fisher): 6.00
P-value (Fisher):    5.9448e-11

Interpreting the result

An odds ratio of 6.0 (95% CI: 3.2 to 11.3) means: in this sample, outdoor workers had 6 times the odds of melanoma compared to indoor workers. The confidence interval does not include 1.0, so the result is consistent with a positive association at the conventional 5% significance level.

One number this is not: a risk ratio. In a case-control study, cases are deliberately oversampled relative to their true frequency in the population, so the table does not reflect actual exposure prevalences. The odds ratio can approximate a risk ratio when the outcome is rare in the population (the rare-disease approximation), but that condition is not met for many cancers, and it is worth stating explicitly rather than assuming.

An odds ratio of 6.0 also does not establish causation. This study controlled for age and sex but not for skin type, family history, recreational sun exposure, or other variables that could confound the relationship. A statistical association, even a strong one, is not a causal effect without the right study design and appropriate adjustment.

Knowledge check

In a second case-control study, researchers found 50 cases exposed and 50 cases unexposed, along with 30 controls exposed and 70 controls unexposed. What is the odds ratio, and does it suggest a positive or negative association?

Show the working and answer

OR = (a × d) ÷ (b × c) = (50 × 70) ÷ (50 × 30) = 3,500 ÷ 1,500 = 2.33. The odds ratio is above 1, which means the exposed group had higher odds of the outcome than the unexposed group. The association is positive. To get the 95% CI: ln(2.33) = 0.846; SE = sqrt(1/50 + 1/50 + 1/30 + 1/70) = sqrt(0.02 + 0.02 + 0.0333 + 0.0143) = sqrt(0.0876) = 0.296; lower = exp(0.846 − 1.96 × 0.296) = exp(0.266) = 1.30; upper = exp(0.846 + 0.580) = exp(1.426) = 4.16. So OR = 2.33 (95% CI: 1.30, 4.16).

Common errors

  • Transposing the table. If you swap rows or columns, the OR inverts. Always label the array explicitly and check the cell values before computing.
  • Using Pearson chi-squared with small cells. When any expected cell count falls below 5, prefer Fisher’s exact test.
  • Reporting OR without a confidence interval. A point estimate with no interval is not enough. Report both.
  • Calling the OR a risk ratio. In a case-control study, only the OR is estimable without external prevalence data. Do not label it a relative risk unless the study design permits it.

Tested with Python 3.12, NumPy 2.2, and SciPy 1.15. If your confidence interval shows slightly different decimal places, check that your standard-error formula matches the Woolf method used here.

Humanities Moment

Claude Monet

French painter · 1840–1926

Monet was the most widely known French Impressionist painter and worked prolifically into his eighties despite deteriorating eyesight. His series paintings, including the haystacks, Rouen Cathedral, and London fog studies, returned to the same subject under different light conditions to record how the same scene could appear entirely different depending on when and how it was observed.

Why this work: Ships Riding on the Seine at Rouen captures a busy commercial river at a specific moment in time. An odds ratio is also a snapshot: it describes the association between an exposure and an outcome in a particular sample, at a particular time, with a particular comparison group. Monet’s views of the Seine changed with the weather, the season, and the vantage point. Odds ratios change with the study population, the exposure definition, and the variables that were or were not controlled for. Both reward careful attention to conditions. The painting is the article’s featured image and was sourced from Artvee by Broadly Epi.

Sources and further reading

Concept package

Continue from the method

  • Odds ratio
  • Case-control study
  • Relative risk
  • Confidence intervals
  • 2x2 contingency table
Browse Epi Explained