set_weights
set_weights(*specs, **named)Set a survey weighting scheme for the session.
Defines target shares for one or more categorical variables (e.g. a known population split by gender or region). Once set, the summary helpers (calc_percentage(), calc_nps(), calc_summary(), crosstab()) weight their results automatically, so the weighted margins match your targets. Pass weights=False to any of them to opt out for a single call.
With a single variable the weights are exact post-stratification: target_share / sample_share for each category. With several variables the weights are found by raking (iterative proportional fitting) so every variable’s weighted margin matches its targets. Weights are normalised to mean 1 (so the weighted base equals the sample size), and respondents whose weighting value is blank or a non-answer (see na_blank()) are left unadjusted. A category that appears in the data but is missing from your targets is an error: give every observed category a share. If a default dataset is set, this reports the Kish design effect and the effective sample size so you can see the precision cost.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| *specs | dict | One scheme per variable carrying a variable entry and a share per category: {"variable": "demo_gender", "Male": 0.49, "Female": 0.50, "Non-binary": 0.01}. A list of such dicts, or a dict of target dicts keyed by variable, also works. Shares need not sum to 1; they are normalised per variable (so raw percentages or counts work too). |
() |
| **named | dict | The named form: demo_gender={"Male": 0.49, "Female": 0.50}, where the keyword is the column. |
{} |
Returns
| Name | Type | Description |
|---|---|---|
| dict | The parsed scheme: normalised targets keyed by variable. |
See Also
clear_weights, get_weights, weight_vector, calc_percentage
Examples
>>> set_weights({"variable": "demo_gender",
... "Male": 0.49, "Female": 0.50, "Non-binary": 0.01})
>>> calc_percentage(podracing_survey, "satis_return")
>>> clear_weights()