Formulaic Contrasts

1.0.0 · active · verified Sat Apr 11

Formulaic Contrasts (version 1.0.0) is a Python library designed to build contrast vectors for statistical models defined using the `formulaic` library. It provides tools for conveniently constructing design matrices and specifying comparisons between categorical levels. The library released its 1.0.0 version, declaring the API as stable, and is part of the scverse project. Its release cadence is irregular but indicates movement towards stability.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `FormulaicContrasts` with a pandas DataFrame and a formulaic design string. It then shows two ways to build contrast vectors: using the flexible `cond()` method for arbitrary conditions and arithmetic combinations, and the `contrast()` method for simple pairwise comparisons between levels of a single variable.

import pandas as pd
from formulaic_contrasts import FormulaicContrasts
from formulaic_contrasts.datasets import treatment_response

# Load example data
df = treatment_response()

# Initialize FormulaicContrasts with data and a formulaic design string
model = FormulaicContrasts(df, '~ response + treatment')

# Build a contrast for 'responder' vs 'non_responder'
# using the more general .cond() method
contrast_vector = model.cond(response='responder') - model.cond(response='non_responder')

print("Contrast Vector (responder vs non_responder):")
print(contrast_vector)

# Build a simple pairwise contrast using .contrast()
simple_contrast = model.contrast(
    column='treatment',
    baseline='drugA',
    group_to_compare='drugB'
)

print("\nSimple Contrast Vector (drugB vs drugA):")
print(simple_contrast)

view raw JSON →