datagrid
datagrid
Functions
Name | Description |
---|---|
datagrid | Data grids |
datagrid
datagrid.datagrid(=None,
model=None,
newdata='mean_or_mode',
grid_type=lambda x: x.mean(),
FUN_numeric=lambda x: x.mode()[0],
FUN_other**kwargs,
)
Data grids
Generate a data grid of user-specified values for use in the ‘newdata’ argument of the ‘predictions()’, ‘comparisons()’, and ‘slopes()’ functions. This is useful to define where in the predictor space we want to evaluate the quantities of interest. Ex: the predicted outcome or slope for a 37 year old college graduate.
Parameters:
model
: Model objectnewdata
: DataFrame (one and only one of themodel
andnewdata
arguments can be used.)grid_type
: Determines the functions to apply to each variable. The defaults can be overridden by defining individual variables explicitly in...
, or by supplying a function to one of theFUN_*
arguments.- “mean_or_mode”: Character, factor, logical, and binary variables are set to their modes. Numeric, integer, and other variables are set to their means.
- “balanced”: Each unique level of character, factor, logical, and binary variables are preserved. Numeric, integer, and other variables are set to their means. Warning: When there are many variables and many levels per variable, a balanced grid can be very large. In those cases, it is better to use
grid_type="mean_or_mode"
and to specify the unique levels of a subset of named variables explicitly. - “counterfactual”: the entire dataset is duplicated for each combination of the variable values specified in
...
. Variables not explicitly supplied todatagrid()
are set to their observed values in the original dataset.
FUN_numeric
: The function to be applied to numeric variables.FUN_other
: The function to be applied to other variable types.
Returns:
A Polars DataFrame in which each row corresponds to one combination of the named predictors supplied by the user. Variables which are not explicitly defined are held at their mean or mode.
Examples:
```python import polars as pl import statsmodels.formula.api as smf from marginaleffects import * mtcars = pl.read_csv(“https://vincentarelbundock.github.io/Rdatasets/csv/datasets/mtcars.csv”)
The output only has 2 rows, and all the variables except hp
are at their mean or mode.
datagrid(newdata = mtcars, hp = [100, 110])
We get the same result by feeding a model instead of a DataFrame
mod = smf.ols(“mpg ~ hp * qsec”, mtcars).fit() datagrid(model = mod, hp = [100, 110])
Use in marginaleffects
to compute “Typical Marginal Effects”. When used in slopes()
or predictions()
we do not need to specify the model
or newdata
arguments.
nd = datagrid(mod, hp = [100, 110]) slopes(mod, newdata = nd)
The full dataset is duplicated with each observation given counterfactual values of 100 and 110 for the hp
variable. The original mtcars
includes 32 rows, so the resulting dataset includes 64 rows.
dg = datagrid(newdata = mtcars, hp = [100, 110], grid_type = “counterfactual”) print(dg.shape)