Skip to main content

Stratified random assignment using pandas

Project description

Stochatreat

Build typing-and-tests Coverage Status
PyPI pypi PyPI Downloads
conda-forge Conda conda-downloads
Meta Hatch project linting - Ruff types - Mypy License - MIT

Introduction

This is a Python tool to employ stratified randomization or sampling with uneven numbers in some strata using pandas. Mainly thought with randomized controlled trials (RCTs) in mind, it also works for any other scenario in where you would like to randomly allocate treatment within blocks or strata. The tool also supports having multiple treatments with different probability of assignment within each block or stratum.

Installation

PyPI

You can install this package via pip:

pip install stochatreat

Conda

You can also install this package with conda:

conda install -c conda-forge stochatreat

Usage

Single cluster:

from stochatreat import stochatreat
import numpy as np
import pandas as pd

# make 1000 households in 5 different neighborhoods.
np.random.seed(42)
df = pd.DataFrame(
    data={"id": list(range(1000)), "nhood": np.random.randint(1, 6, size=1000)}
)

# randomly assign treatments by neighborhoods.
treats = stochatreat(
    data=df,  # your dataframe
    stratum_cols="nhood",  # the blocking variable
    treats=2,  # including control
    idx_col="id",  # the unique id column
    random_state=42,  # random seed
    misfit_strategy="stratum",
)  # the misfit strategy to use
# merge back with original data
df = df.merge(treats, how="left", on="id")

# check for allocations
df.groupby("nhood")["treat"].value_counts().unstack()

# previous code should return this
treat    0    1
nhood
1      105  105
2       95   95
3       95   95
4      103  103
5      102  102

Multiple clusters and treatment probabilities:

from stochatreat import stochatreat
import numpy as np
import pandas as pd

# make 1000 households in 5 different neighborhoods, with a dummy indicator
np.random.seed(42)
df = pd.DataFrame(
    data={
        "id": list(range(1000)),
        "nhood": np.random.randint(1, 6, size=1000),
        "dummy": np.random.randint(0, 2, size=1000),
    }
)

# randomly assign treatments by neighborhoods and dummy status.
treats = stochatreat(
    data=df,
    stratum_cols=["nhood", "dummy"],
    treats=2,
    probs=[1 / 3, 2 / 3],
    idx_col="id",
    random_state=42,
    misfit_strategy="global",
)
# merge back with original data
df = df.merge(treats, how="left", on="id")

# check for allocations
df.groupby(["nhood", "dummy"])["treat"].value_counts().unstack()

# previous code should return this
treat         0   1
nhood dummy
1     0      37  75
      1      33  65
2     0      35  69
      1      29  57
3     0      30  58
      1      34  68
4     0      36  72
      1      32  66
5     0      33  68
      1      35  68

Contributing

If you'd like to contribute to the package, make sure you read the contributing guide.

References

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

stochatreat-0.1.5.tar.gz (20.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

stochatreat-0.1.5-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

Details for the file stochatreat-0.1.5.tar.gz.

File metadata

  • Download URL: stochatreat-0.1.5.tar.gz
  • Upload date:
  • Size: 20.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Hatch/1.16.3 cpython/3.13.6 HTTPX/0.28.1

File hashes

Hashes for stochatreat-0.1.5.tar.gz
Algorithm Hash digest
SHA256 6e5cddd8ca7e6fc4a790c67e264c0b9bf56fb6622c1b9059969d57790ff8d646
MD5 dc75d7f8a3852b4963f6c45a02c3b556
BLAKE2b-256 1f61dd35ccf4e55f114d696bd131ec7c4d930e49d94335d95b1117b3e66678e2

See more details on using hashes here.

File details

Details for the file stochatreat-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: stochatreat-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 8.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Hatch/1.16.3 cpython/3.13.6 HTTPX/0.28.1

File hashes

Hashes for stochatreat-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 5f116e496db9eec96d8816813aae36d46d2325ef389507371bff1aa353a16c55
MD5 f53cdfee40063dad3641038ba8b1c49b
BLAKE2b-256 3226458e60cfd52e505918fabb85f621eacb1cbcfac93a4f22d430ab8f402de5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page