Metadata-Version: 2.5
Name: simpsonscan
Version: 0.1.0
Summary: Find Simpson's paradoxes hiding in your pandas data: trends and rates that reverse when you split the data into groups.
Project-URL: Homepage, https://github.com/AnmolAdhikari/simpsonscan
Project-URL: Issues, https://github.com/AnmolAdhikari/simpsonscan/issues
Project-URL: Changelog, https://github.com/AnmolAdhikari/simpsonscan/blob/main/CHANGELOG.md
Author-email: Anmol Adhikari <anmoladhikari03@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: ab-testing,causal-inference,confounding,data-analysis,data-literacy,education,pandas,simpsons-paradox,statistics
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Education
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: numpy>=1.23
Requires-Dist: pandas>=2.0
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: matplotlib>=3.7; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Provides-Extra: plot
Requires-Dist: matplotlib>=3.7; extra == 'plot'
Description-Content-Type: text/markdown

# simpsonscan

**Find the Simpson's paradoxes hiding in your data, automatically.**

A Simpson's paradox happens when a trend that appears in a whole dataset *reverses* once you split it into groups. It shows up in medicine, hiring, A/B tests and sports statistics, and it quietly turns correct numbers into wrong conclusions.

`simpsonscan` checks every column against every other column of a pandas DataFrame and tells you where the story flips, by how much, and why.

```bash
pip install simpsonscan            # or "simpsonscan[plot]" to include matplotlib for charts
```

![UC Berkeley 1973: men look favoured overall, but women do better in 4 of 6 departments](https://raw.githubusercontent.com/AnmolAdhikari/simpsonscan/main/docs/berkeley.svg)

## The classic: UC Berkeley admissions, 1973

In 1973, 44.5% of men but only 30.4% of women were admitted to Berkeley's graduate school, which looked like clear bias against women. Look department by department, though, and the picture flips:

```python
import simpsonscan

df = simpsonscan.load_berkeley()     # one row per (department, gender, admitted) with counts
simpsonscan.scan(df, target="admitted", weights="count")
```

```
SimpsonScan  target='admitted'  rows=24  combinations checked=2
------------------------------------------------------------
[1] 'gender' -> 'admitted' reverses within 'department': 'Male' vs 'Female'
      overall:  'Male' has the higher rate by +14.2 pp
      adjusted for 'department': 'Female' is higher by +4.3 pp (4 of 6 groups favour 'Female')
      why: 'Female' is concentrated in 'department' groups where 'admitted' is low (their mix alone predicts 29.5% vs 45.1% for 'Male'; 32% of 'Female' is in 'C').
      evidence: both effects are at least 2.3 standard errors from zero
```

Women mostly applied to the departments that admitted few applicants of either gender. Nobody told `simpsonscan` to look at gender or department: it scanned every combination and found the reversal itself.

## Trends reverse too

```python
df = simpsonscan.make_example()      # synthetic: exercise vs cholesterol by age group
report = simpsonscan.scan(df, target="cholesterol")
report[0].plot()
```

```
[1] 'exercise_hours' -> 'cholesterol' trend reverses within 'age_group'
      overall correlation:      r = +0.85
      within 'age_group' groups: r = -0.49 (4 of 4 groups go the other way)
      why: 'age_group' groups with higher 'exercise_hours' also have higher 'cholesterol' (r = +1.00 between group means), which hides the negative relationship inside each group.
      evidence: both effects are at least 13.6 standard errors from zero
```

Looking at everyone, more exercise seems to go with *higher* cholesterol. Inside every age group it goes with *lower* cholesterol. Older people both exercise more and have higher cholesterol.

## Use it on your own data

```python
report = simpsonscan.scan(df, target="converted")    # check everything
report.to_frame()                                    # findings as a DataFrame
report[0].table                                      # the group-by-group numbers
report[0].plot()                                     # the before/after chart

# or ask one specific question
simpsonscan.check(df, "treatment", "recovered", by="severity")
```

- **Target:** any numeric or boolean column. Booleans and 0/1 are treated as rates.
- **Categorical predictors** (e.g. treatment, gender, variant) are compared with *rate/mean reversals*.
- **Numeric predictors** (e.g. dose, hours, price) are compared with *trend reversals*: the sign of the overall correlation versus the pooled within-group correlation.
- **Conditioners** can be categorical columns, or numeric columns cut into quantile bins (`bins=4`).
- **Aggregated tables** work with `weights="count"`.

## Built to avoid false alarms

A paradox is only reported if:

1. the overall effect and the group-adjusted effect point in **opposite directions**;
2. **both** are at least `min_z` standard errors from zero (default 2.0), so small noisy groups can't fake a reversal;
3. both are practically meaningful (`min_effect`, `min_corr`), and every group has at least `min_group` rows.

The test suite scans hundreds of random datasets with no paradox, plus confounded data where the effect keeps its direction; none of them trigger a finding. Findings are ranked by strength, strongest first.

| Parameter | Default | Meaning |
|---|---|---|
| `min_z` | `2.0` | both effects must be this many standard errors from zero |
| `min_effect` | `0.05` | categorical: minimum gap in standard deviations of the target |
| `min_corr` | `0.1` | numeric: minimum correlation, overall and within groups |
| `min_group` | `20` | smallest group (rows or total weight) to use |
| `max_levels` | `12` | columns with at most this many values count as categorical |
| `bins` | `4` | quantile bins for numeric conditioners (`None` to skip) |

## How it works

- **Rate / mean reversal:** for each pair of predictor levels, the overall difference is compared with the *adjusted* difference: the within-group differences averaged with the groups' sizes as weights (direct standardisation). Standard errors come from the within-cell variances.
- **Trend reversal:** the overall weighted Pearson correlation is compared with the pooled within-group correlation (after removing each group's mean), with a t-statistic for each.
- **Explanations** come from the composition of the groups: where each level sits, and how high the target is in those groups.

## References

- Bickel, P. J., Hammel, E. A., & O'Connell, J. W. (1975). Sex bias in graduate admissions: Data from Berkeley. *Science*, 187(4175), 398–404.
- Simpson, E. H. (1951). The interpretation of interaction in contingency tables. *Journal of the Royal Statistical Society B*, 13(2), 238–241.

## Development

```bash
pip install -e ".[dev]"
pytest
```

## License

MIT
