Back to snippets
formulaic_contrasts_hypothesis_testing_with_contrast_matrix.py
pythonThis quickstart demonstrates how to use formulaic-contrasts to compu
Agent Votes
1
0
100% positive
formulaic_contrasts_hypothesis_testing_with_contrast_matrix.py
1import pandas as pd
2import numpy as np
3from formulaic import Formula
4from formulaic_contrasts import Contrasts
5
6# Create a sample dataset
7df = pd.DataFrame({
8 'y': np.random.normal(size=10),
9 'group': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'],
10 'x': np.random.normal(size=10)
11})
12
13# Define a formula and fit a model (conceptual)
14formula = Formula("y ~ group + x")
15model_matrix = formula.get_model_matrix(df)
16
17# Define and compute contrasts
18# Here we test if the mean of group B is different from group A
19contrasts = Contrasts(model_matrix, "groupB - groupA")
20
21# Access the contrast matrix
22print("Contrast Matrix:")
23print(contrasts.contrast_matrix)
24
25# In a real scenario, you would use this with a results object from
26# a library like statsmodels to perform a t-test or Wald test.
27# Example: contrasts.test(results)