stochatreat


Namestochatreat JSON
Version 0.0.19 PyPI version JSON
download
home_pageNone
SummaryStratified random assignment using pandas
upload_time2024-04-28 09:34:57
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseNone
keywords block randomization randomization strata stratified random assignment stratified randomization
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Stochatreat

| | |
|---|---|
|Build|[![Main Branch Tests](https://github.com/manmartgarc/stochatreat/actions/workflows/release.yml/badge.svg?branch=main)](https://github.com/manmartgarc/stochatreat/actions/workflows/test.yml) [![codecov](https://codecov.io/gh/manmartgarc/stochatreat/graph/badge.svg?token=llPoW2rWIN)](https://codecov.io/gh/manmartgarc/stochatreat)
|PyPI| [![pypi](https://img.shields.io/pypi/v/stochatreat?logo=pypi)](https://pypi.org/project/stochatreat/) ![pypi-downloads](https://img.shields.io/pypi/dm/stochatreat?logo=pypi)
|conda-forge| [![Conda](https://img.shields.io/conda/v/conda-forge/stochatreat?logo=conda-forge)](https://anaconda.org/conda-forge/stochatreat) ![conda-downloads](https://img.shields.io/conda/dn/conda-forge/stochatreat?logo=conda-forge)
|Meta| [![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch) [![linting - Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) [![types - Mypy](https://img.shields.io/badge/types-Mypy-blue.svg)](https://github.com/python/mypy) [![License - MIT](https://img.shields.io/badge/license-MIT-9400d3.svg)](https://spdx.org/licenses/)

---

## 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`:

```bash
pip install stochatreat
```

### Conda

You can also install this package with `conda`:

```bash
conda install -c conda-forge stochatreat
```

## Usage

Single cluster:

```python
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:

```python
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](https://github.com/manmartgarc/stochatreat/blob/main/.github/CONTRIBUTING.md).

## References

- `stochatreat` is totally inspired by [Alvaro Carril's](https://acarril.github.io/) fantastic STATA package: [`randtreat`](https://acarril.github.io/posts/randtreat), which was published in [The Stata Journal](https://www.stata-journal.com/article.html?article=st0490).
- [David McKenzie's](http://blogs.worldbank.org/impactevaluations/tools-of-the-trade-doing-stratified-randomization-with-uneven-numbers-in-some-strata) fantastic post (and blog) about running RCTs for the World Bank.
- [*In Pursuit of Balance: Randomization in Practice in Development Field Experiments.* Bruhn, McKenzie, 2009](https://www.aeaweb.org/articles?id=10.1257/app.1.4.200)

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "stochatreat",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "block randomization, randomization, strata, stratified random assignment, stratified randomization",
    "author": null,
    "author_email": "Manuel Martinez <manmartgarc@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/7e/fb/0cd41dcee96f0f2daf6ffd32165ebf5e9baa77ceb1e59507056ae9dcaa4e/stochatreat-0.0.19.tar.gz",
    "platform": null,
    "description": "# Stochatreat\n\n| | |\n|---|---|\n|Build|[![Main Branch Tests](https://github.com/manmartgarc/stochatreat/actions/workflows/release.yml/badge.svg?branch=main)](https://github.com/manmartgarc/stochatreat/actions/workflows/test.yml) [![codecov](https://codecov.io/gh/manmartgarc/stochatreat/graph/badge.svg?token=llPoW2rWIN)](https://codecov.io/gh/manmartgarc/stochatreat)\n|PyPI| [![pypi](https://img.shields.io/pypi/v/stochatreat?logo=pypi)](https://pypi.org/project/stochatreat/) ![pypi-downloads](https://img.shields.io/pypi/dm/stochatreat?logo=pypi)\n|conda-forge| [![Conda](https://img.shields.io/conda/v/conda-forge/stochatreat?logo=conda-forge)](https://anaconda.org/conda-forge/stochatreat) ![conda-downloads](https://img.shields.io/conda/dn/conda-forge/stochatreat?logo=conda-forge)\n|Meta| [![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch) [![linting - Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) [![types - Mypy](https://img.shields.io/badge/types-Mypy-blue.svg)](https://github.com/python/mypy) [![License - MIT](https://img.shields.io/badge/license-MIT-9400d3.svg)](https://spdx.org/licenses/)\n\n---\n\n## Introduction\n\nThis 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.\n\n## Installation\n\n### PyPI\n\nYou can install this package via `pip`:\n\n```bash\npip install stochatreat\n```\n\n### Conda\n\nYou can also install this package with `conda`:\n\n```bash\nconda install -c conda-forge stochatreat\n```\n\n## Usage\n\nSingle cluster:\n\n```python\nfrom stochatreat import stochatreat\nimport numpy as np\nimport pandas as pd\n\n# make 1000 households in 5 different neighborhoods.\nnp.random.seed(42)\ndf = pd.DataFrame(\n    data={\"id\": list(range(1000)), \"nhood\": np.random.randint(1, 6, size=1000)}\n)\n\n# randomly assign treatments by neighborhoods.\ntreats = stochatreat(\n    data=df,  # your dataframe\n    stratum_cols=\"nhood\",  # the blocking variable\n    treats=2,  # including control\n    idx_col=\"id\",  # the unique id column\n    random_state=42,  # random seed\n    misfit_strategy=\"stratum\",\n)  # the misfit strategy to use\n# merge back with original data\ndf = df.merge(treats, how=\"left\", on=\"id\")\n\n# check for allocations\ndf.groupby(\"nhood\")[\"treat\"].value_counts().unstack()\n\n# previous code should return this\ntreat    0    1\nnhood\n1      105  105\n2       95   95\n3       95   95\n4      103  103\n5      102  102\n```\n\nMultiple clusters and treatment probabilities:\n\n```python\nfrom stochatreat import stochatreat\nimport numpy as np\nimport pandas as pd\n\n# make 1000 households in 5 different neighborhoods, with a dummy indicator\nnp.random.seed(42)\ndf = pd.DataFrame(\n    data={\n        \"id\": list(range(1000)),\n        \"nhood\": np.random.randint(1, 6, size=1000),\n        \"dummy\": np.random.randint(0, 2, size=1000),\n    }\n)\n\n# randomly assign treatments by neighborhoods and dummy status.\ntreats = stochatreat(\n    data=df,\n    stratum_cols=[\"nhood\", \"dummy\"],\n    treats=2,\n    probs=[1 / 3, 2 / 3],\n    idx_col=\"id\",\n    random_state=42,\n    misfit_strategy=\"global\",\n)\n# merge back with original data\ndf = df.merge(treats, how=\"left\", on=\"id\")\n\n# check for allocations\ndf.groupby([\"nhood\", \"dummy\"])[\"treat\"].value_counts().unstack()\n\n# previous code should return this\ntreat         0   1\nnhood dummy\n1     0      37  75\n      1      33  65\n2     0      35  69\n      1      29  57\n3     0      30  58\n      1      34  68\n4     0      36  72\n      1      32  66\n5     0      33  68\n      1      35  68\n```\n\n## Contributing\n\nIf you'd like to contribute to the package, make sure you read the [contributing guide](https://github.com/manmartgarc/stochatreat/blob/main/.github/CONTRIBUTING.md).\n\n## References\n\n- `stochatreat` is totally inspired by [Alvaro Carril's](https://acarril.github.io/) fantastic STATA package: [`randtreat`](https://acarril.github.io/posts/randtreat), which was published in [The Stata Journal](https://www.stata-journal.com/article.html?article=st0490).\n- [David McKenzie's](http://blogs.worldbank.org/impactevaluations/tools-of-the-trade-doing-stratified-randomization-with-uneven-numbers-in-some-strata) fantastic post (and blog) about running RCTs for the World Bank.\n- [*In Pursuit of Balance: Randomization in Practice in Development Field Experiments.* Bruhn, McKenzie, 2009](https://www.aeaweb.org/articles?id=10.1257/app.1.4.200)\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Stratified random assignment using pandas",
    "version": "0.0.19",
    "project_urls": {
        "Documentation": "https://github.com/manmartgarc/stochatreat/blob/main/README.md",
        "Issues": "https://github.com/manmartgarc/stochatreat/issues",
        "Source": "https://github.com/manmartgarc/stochatreat/"
    },
    "split_keywords": [
        "block randomization",
        " randomization",
        " strata",
        " stratified random assignment",
        " stratified randomization"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "6ede89f950703012edc640552e500f1e61843cf4b34d9881d80dd6dcfe5d0f64",
                "md5": "f638db4ed79b13b06975bc0dd57f83ee",
                "sha256": "7e93a727c71a48a8b45da1ec329deb3af66797e37003d0fa94e81ef7386b95ef"
            },
            "downloads": -1,
            "filename": "stochatreat-0.0.19-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "f638db4ed79b13b06975bc0dd57f83ee",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 7960,
            "upload_time": "2024-04-28T09:34:55",
            "upload_time_iso_8601": "2024-04-28T09:34:55.343501Z",
            "url": "https://files.pythonhosted.org/packages/6e/de/89f950703012edc640552e500f1e61843cf4b34d9881d80dd6dcfe5d0f64/stochatreat-0.0.19-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "7efb0cd41dcee96f0f2daf6ffd32165ebf5e9baa77ceb1e59507056ae9dcaa4e",
                "md5": "5c4c33319e9283b99d1669fba6b39f1f",
                "sha256": "a2bd1ff8d62f3adca4f78b4252da57ff9a3ea45c4dd11a121d24022258d0359b"
            },
            "downloads": -1,
            "filename": "stochatreat-0.0.19.tar.gz",
            "has_sig": false,
            "md5_digest": "5c4c33319e9283b99d1669fba6b39f1f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 12972,
            "upload_time": "2024-04-28T09:34:57",
            "upload_time_iso_8601": "2024-04-28T09:34:57.025099Z",
            "url": "https://files.pythonhosted.org/packages/7e/fb/0cd41dcee96f0f2daf6ffd32165ebf5e9baa77ceb1e59507056ae9dcaa4e/stochatreat-0.0.19.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-28 09:34:57",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "manmartgarc",
    "github_project": "stochatreat",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "stochatreat"
}
        
Elapsed time: 0.27838s