typestar

Proportions and power in Python

A z-test for proportions, and the sample size that would detect an effect.

import numpy as np
from statsmodels.stats.multitest import multipletests
from statsmodels.stats.power import TTestIndPower
from statsmodels.stats.proportion import proportions_ztest

statistic, pvalue = proportions_ztest(count=np.array([62, 45]),
                                      nobs=np.array([120, 120]))
print(round(statistic, 3), round(pvalue, 5))

raw = [0.001, 0.012, 0.03, 0.2, 0.6]
reject, adjusted, _, _ = multipletests(raw, alpha=0.05, method="holm")
print(reject.tolist())
print([round(p, 4) for p in adjusted])

needed = TTestIndPower().solve_power(effect_size=0.4, power=0.8, alpha=0.05)
print(f"{needed:.0f} per group")

How it works

  1. proportions_ztest takes successes and totals.
  2. multipletests corrects a family of p-values.
  3. TTestIndPower.solve_power answers how many rows you need.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
600
Tokens
166
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 91 seconds.

Type this snippet

Step 4 of 4 in Beyond least squares, step 12 of 19 in Statistics with statsmodels.

← Previous Next →