Propensity Score Matching and IPW in Python (with a Love Plot)

Estimate a treatment effect from observational data in Python with propensity scores: fit them with scikit-learn, reweight with IPW, match on them, and check covariate balance with a love plot.

When people choose whether to get a treatment (a training program, a feature, a coupon), comparing the two groups directly mixes the treatment effect with who chose it. A propensity score is each person's estimated probability of getting the treatment given their covariates. In Python you fit it with a scikit-learn LogisticRegression, then either reweight people by 1 / propensity (inverse probability weighting, IPW) or match each treated person to a control with a similar score. The code below uses scikit-learn 1.9 and statsmodels 0.14.

Quick Example

This simulates a job-training program where people with lower prior income and less education enroll more often. The true effect of the program on income is +$2k per year. Enrollment is not randomized, so the naive comparison is biased:

import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression

rng = np.random.default_rng(23)
n = 4000
age = rng.normal(38, 10, n).clip(20, 65)
educ = rng.normal(13, 2.5, n).clip(8, 20)
prior_income = rng.normal(35, 10, n).clip(10, None) + 1.2 * (educ - 13)   # $k
urban = rng.binomial(1, 0.6, n)

# Lower prior income and less education make enrollment more likely
logit_t = 0.6 - 0.07 * (prior_income - 35) - 0.25 * (educ - 13) + 0.03 * (age - 38) + 0.4 * urban
treated = rng.random(n) < 1 / (1 + np.exp(-logit_t))
true_effect = 2.0   # $k per year
income = (8 + 0.8 * prior_income + 1.1 * educ + 0.05 * age + 1.5 * urban
          + true_effect * treated + rng.normal(0, 5, n))
df = pd.DataFrame({"age": age, "educ": educ, "prior_income": prior_income,
                   "urban": urban, "treated": treated.astype(int), "income": income})
covs = ["age", "educ", "prior_income", "urban"]

# 1. Propensity scores
Xs = (df[covs] - df[covs].mean()) / df[covs].std()
df["ps"] = LogisticRegression(max_iter=1000).fit(Xs, df.treated).predict_proba(Xs)[:, 1]

# 2. Stabilized inverse probability weights
p_treat = df.treated.mean()
df["w"] = np.where(df.treated == 1, p_treat / df.ps, (1 - p_treat) / (1 - df.ps))

# 3. Weighted difference in means
def wmean(x, w):
    return np.sum(x * w) / np.sum(w)

def ipw_ate(d):
    t, c = d[d.treated == 1], d[d.treated == 0]
    return wmean(t.income, t.w) - wmean(c.income, c.w)

naive = df.income[df.treated == 1].mean() - df.income[df.treated == 0].mean()
print(f"naive difference: {naive:.2f}")
print(f"IPW estimate:     {ipw_ate(df):.2f}")

The naive comparison says the program lowers income by about $5.98k per year. The IPW estimate is $2.19k, close to the true +$2.0k. Enrolled people had lower incomes to begin with, so comparing raw averages punishes the program for who joined it.

Why Can't I Just Compare the Two Groups?

Confounders are variables that affect both who gets the treatment and the outcome. Here, prior income and education push people toward the program and also raise later income. The groups differ before the program starts, so the gap afterward mixes the two. Random assignment would break the link between covariates and treatment. Without it, you have to adjust for the covariates.

Propensity scores reduce all the covariates to one number, the probability of treatment. The key result: among people with the same propensity, treatment is as good as random with respect to the measured covariates. You only need to balance on that one score, not on every covariate combination.

Check Overlap Before You Estimate Anything

Adjustment only works where both groups exist. A histogram of propensity scores by group shows it:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(7.5, 4.3))
bins = np.linspace(0, 1, 41)
ax.hist(df.loc[df.treated == 0, "ps"], bins=bins, alpha=0.65, color="#0ea5e9", label="Not enrolled")
ax.hist(df.loc[df.treated == 1, "ps"], bins=bins, alpha=0.65, color="#f97316", label="Enrolled")
ax.set(xlabel="Propensity score (estimated probability of enrolling)", ylabel="People",
       title="Overlap check: propensity scores by group")
ax.legend()

Overlapping histograms of propensity scores for enrolled and not-enrolled people, with the not-enrolled group concentrated at low scores and the enrolled group at high scores but both covering most of the range

Enrolled people (orange) pile up at high scores and non-enrolled people (blue) at low ones, but both groups have people across most of the range, from about 0.1 to 0.95. That overlap is what lets us compare like with like. If a region had only treated people (scores near 1 with no controls), no method could estimate the effect there. In that case, trim to the overlapping region before you estimate.

Inverse Probability Weighting (IPW)

IPW gives each person a weight that makes the treated and control groups look like the whole sample. People who were unlikely to get the treatment but did get it count for more, and likewise for controls who were likely to be treated. p_treat / ps for the treated and (1 - p_treat) / (1 - ps) for controls are the stabilized weights. Stabilizing keeps the weights near 1 on average, which makes extreme ones easy to spot. Because wmean divides by the sum of the weights, the estimate is the same as with raw 1 / ps weights.

Check the weights for extremes. df.w.max() is 11.5 here, which is fine. A weight in the hundreds means one person is driving the result, and you should trim the sample or cap the weights.

IPW estimates the average treatment effect (ATE): the effect if everyone in the sample were treated versus nobody.

Match on the Propensity Score

Matching pairs each treated person with the control whose propensity is closest, then compares outcomes within pairs. This version matches with replacement on the logit of the score, with a caliper of 0.2 standard deviations so poor matches are dropped:

from sklearn.neighbors import NearestNeighbors

def match_att(d, caliper_sd=0.2):
    logit_ps = np.log(d.ps / (1 - d.ps)).to_numpy()
    caliper = caliper_sd * logit_ps.std()
    t_idx = np.where(d.treated.to_numpy() == 1)[0]
    c_idx = np.where(d.treated.to_numpy() == 0)[0]
    nn = NearestNeighbors(n_neighbors=1).fit(logit_ps[c_idx].reshape(-1, 1))
    dist, pos = nn.kneighbors(logit_ps[t_idx].reshape(-1, 1))
    keep = dist[:, 0] <= caliper
    return t_idx[keep], c_idx[pos[keep, 0]]

t_rows, c_rows = match_att(df)
att_match = df.income.iloc[t_rows].mean() - df.income.iloc[c_rows].mean()
print(f"matched pairs: {len(t_rows)} of {int(df.treated.sum())} treated")
print(f"unique controls used: {len(set(c_rows))}")
print(f"matched ATT: {att_match:.2f}")

All but 25 of the 2,660 treated people found a match within the caliper, using 781 distinct controls (some controls are matched to several treated people, which is what "with replacement" allows). The matched estimate is $1.75k.

Matching estimates the average treatment effect on the treated (ATT): the effect for the kind of people who enrolled. It can differ from the ATE if the effect varies across people. In this simulation the effect is the same for everyone, so both should land near $2k.

Did the Adjustment Work? Check Balance with a Love Plot

The propensity score is only useful if it balances the covariates. A love plot shows the standardized mean difference (SMD) for each covariate before and after adjustment. The common rule of thumb is that an absolute SMD below 0.1 counts as balanced:

def smd(x, t, w=None):
    w = np.ones(len(x)) if w is None else w
    m1, m0 = wmean(x[t == 1], w[t == 1]), wmean(x[t == 0], w[t == 0])
    v1 = np.average((x[t == 1] - m1) ** 2, weights=w[t == 1])
    v0 = np.average((x[t == 0] - m0) ** 2, weights=w[t == 0])
    return (m1 - m0) / np.sqrt((v1 + v0) / 2)

t = df.treated.to_numpy()
matched = df.iloc[np.r_[t_rows, c_rows]]
bal = pd.DataFrame({
    c: {"Unadjusted": smd(df[c].to_numpy(dtype=float), t),
        "IPW": smd(df[c].to_numpy(dtype=float), t, df.w.to_numpy()),
        "Matched": smd(matched[c].to_numpy(dtype=float), matched.treated.to_numpy())}
    for c in covs}).T

fig, ax = plt.subplots(figsize=(7.5, 4.2))
ypos = np.arange(len(bal))[::-1]
for col, color, marker in [("Unadjusted", "#e11d48", "o"), ("IPW", "#0ea5e9", "s"),
                           ("Matched", "#16a34a", "D")]:
    ax.scatter(bal[col].abs(), ypos, color=color, marker=marker, s=60, label=col, zorder=3)
ax.axvline(0.1, color="#64748b", ls="--", lw=1)
ax.set_yticks(ypos, bal.index)
ax.set(xlabel="Absolute standardized mean difference", xlim=(-0.02, None),
       title="Covariate balance before and after adjustment (love plot)")
ax.grid(axis="x", alpha=0.3)
ax.legend(loc="lower right")

Love plot with absolute standardized mean differences for age, educ, prior_income, and urban: unadjusted points are far right near 0.7 to 0.8 for education and prior income, while IPW and matched points all sit left of the 0.1 threshold

Before adjustment, prior income (SMD 0.82) and education (0.71) are badly imbalanced, and age and urban are at about 0.18 and 0.20. After IPW, every covariate is below 0.05. After matching, every covariate is below 0.03. Both methods balanced the covariates they were given.

Report a love plot with any propensity analysis. It is the evidence that the adjustment worked, and a reader can check it without trusting your model. Note that it only covers the covariates you included.

Put Confidence Intervals on the Estimates

The weights and matches both come from an estimated model, so a plain standard error understates the uncertainty. Bootstrap the whole pipeline: resample people, refit the propensity model, and recompute the estimate each time:

def boot_ci(fn, B=300, seed=1):
    r = np.random.default_rng(seed)
    out = []
    for _ in range(B):
        d = df.sample(len(df), replace=True, random_state=int(r.integers(1e9))).reset_index(drop=True)
        Xb = (d[covs] - d[covs].mean()) / d[covs].std()
        d["ps"] = LogisticRegression(max_iter=1000).fit(Xb, d.treated).predict_proba(Xb)[:, 1]
        pt = d.treated.mean()
        d["w"] = np.where(d.treated == 1, pt / d.ps, (1 - pt) / (1 - d.ps))
        out.append(fn(d))
    return np.percentile(out, [2.5, 97.5])

def att_from(d):
    tr, cr = match_att(d)
    return d.income.iloc[tr].mean() - d.income.iloc[cr].mean()

print("IPW 95% CI:     ", boot_ci(ipw_ate).round(2))
print("Matching 95% CI:", boot_ci(att_from).round(2))

For comparison, here is regression adjustment with statsmodels, which simply includes the covariates in an OLS model:

import statsmodels.formula.api as smf

ols = smf.ols("income ~ treated + age + educ + prior_income + urban", df).fit(cov_type="HC1")
print(ols.params["treated"].round(2), ols.conf_int().loc["treated"].round(2).tolist())

Interval chart comparing a naive estimate of minus 5.98 against regression adjustment at 1.90, IPW at 2.19, and propensity matching at 1.75, with a dashed line at the true effect of 2.0 that all three adjusted intervals cross

Method Estimate ($k) 95% interval
Naive difference -5.98 about -6.6 to -5.3
Regression adjustment (OLS) 1.90 1.55 to 2.26
IPW (ATE) 2.19 1.59 to 2.76
Propensity matching (ATT) 1.75 1.16 to 2.37

The naive interval is nowhere near the truth, and all three adjusted intervals cover +2.0. In this simulation the outcome is a simple linear function of the covariates, so plain regression does about as well as the propensity methods. The propensity approaches pay off when the outcome model is hard to get right but the treatment assignment is easier to model.

Which Method Should I Use?

Method Estimates Strengths Watch out for
Regression adjustment ATE under a linear model Simple, efficient Wrong if the outcome model is misspecified
IPW ATE Uses everyone, easy to code Extreme weights when scores are near 0 or 1
Propensity matching ATT Intuitive, easy to audit pairs Discards unmatched people; standard errors need a bootstrap
Doubly robust (IPW + outcome model) ATE Correct if either model is right More code; libraries like EconML or DoWhy help

Practical Tips

  • Only adjust for pre-treatment covariates. Anything measured after the treatment can itself be affected by it, and adjusting for it biases the answer.
  • Include every confounder you can measure. Propensity scores fix imbalance on observed variables only. If something unmeasured drives both enrollment and income (motivation, say), no propensity method fixes it. Say that out loud in any write-up.
  • Standardize before the logistic regression, as above, so LogisticRegression's default regularization treats covariates evenly. Add interaction or squared terms if balance is poor.
  • Don't judge the propensity model by AUC. A very predictive model means little overlap, which makes the estimate harder. Judge it by balance.
  • Randomize when you can. For a real experiment, see A/B test analysis in Python. When rollout dates or a policy change split groups at a fixed time, difference-in-differences can use the time dimension instead.

Similar Topics