Skip to content

Instantly share code, notes, and snippets.

@jdmonaco
Last active February 2, 2021 10:00
Show Gist options
  • Save jdmonaco/5922991 to your computer and use it in GitHub Desktop.
Save jdmonaco/5922991 to your computer and use it in GitHub Desktop.
Welch's t-test for two samples, not assuming equal sample size or variance. Requires Python, NumPy, and SciPy.
from collections import namedtuple
import numpy as np
import scipy.stats as st
TtestResults = namedtuple("Ttest", "T p")
def t_welch(x, y, tails=2):
"""
Welch's t-test for two unequal-size samples, not assuming equal variances
"""
assert tails in (1,2), "invalid: tails must be 1 or 2, found %s"%str(tails)
x, y = np.asarray(x), np.asarray(y)
nx, ny = x.size, y.size
vx, vy = x.var(ddof=1), y.var(ddof=1)
df = ((vx/nx + vy/ny)**2 / # Welch-Satterthwaite equation
((vx/nx)**2 / (nx - 1) + (vy/ny)**2 / (ny - 1)))
t_obs = (x.mean() - y.mean()) / np.sqrt(vx/nx + vy/ny)
p_value = tails * st.t.sf(abs(t_obs), df)
return TtestResults(t_obs, p_value)
@jonkrohn
Copy link

Nice, looks perfect now :)

I checked out your website, btw -- very cool! I did a neuroscience PhD and so naturally get jealous when I see fascinating work like yours by people who stayed on the academic course.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment