pycensus.elections_common¶
Shared machinery for the per-country election loaders.
Pipeline (identical for every country):
- The country loader downloads the finest published result unit
(precinct / polling station / casilla / mesa / poll) plus its polygons and
turns it into a
countsframe indexed by unit id (see :func:build_counts). - :func:
units_to_h3moves the counts to H3 res 8 dasymetrically: every unit's counts are split over the WorldPop 2025 (100 m) pixels whose centre lies inside the unit, proportionally to pixel population (uniformly if the unit has no population pixels), and the pixels are summed into their H3 res-8 cell. Mass-conserving for units that contain at least one pixel centre (tiny units fall back to their centroid cell). - :func:
h3_to_unitsmoves H3 counts onto census geometries, again weighted by WorldPop pixel population (cell value x share of the cell's population that lies in the census unit). - :func:
finalizeturns counts into the shared output columnselec_<scope>_<year>_*(shares are recomputed from the resampled counts, so they are exactly consistent at every geography).
Counts, not shares, are resampled; shares (0-1) are intensive.
PopulationGrid(tif, bbox, res=H3_RES)
¶
WorldPop pixel centres (lon, lat, pop) inside a bbox, with H3 ids.
assign(units, id_col)
¶
Pixels (index = pixel row) with the unit id that contains the centre.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
units
|
GeoDataFrame
|
Polygons. |
required |
id_col
|
str
|
Id column. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
Pixels with |
default_elections_cache(cache_dir=None)
¶
The elections cache folder (created): <cache_dir>/elections or the pycensus elections namespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
Optional[str]
|
Cache folder; |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
The folder. |
slug(name)
¶
Lower-case ASCII slug of a party or candidate name (at most 40 characters).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Any text. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The slug. |
download(url, dest, timeout=300, headers=None)
¶
Download url to dest once (cached). Never bypasses bot challenges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
File URL. |
required |
dest
|
Path
|
Local file. |
required |
timeout
|
int
|
Timeout in seconds. |
300
|
headers
|
Optional[dict]
|
Extra request headers. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
The local file. |
load_blocs(path, election_key)
¶
Return {name: {"bloc": left|right|other, ...}} for one election key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Blocs JSON file. |
required |
election_key
|
str
|
Election key in the file. |
required |
bloc_of(name, blocs)
¶
Bloc of a party or candidate ("other", with a warning, when it is not in the file).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Party / candidate name. |
required |
blocs
|
Dict[str, dict]
|
Dict from :func: |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
build_counts(long, blocs, unit_col='unit', name_col='party', votes_col='votes', blank=None, electors=None, ballots=None, rejected=None)
¶
Long (unit, party, votes) -> wide counts per unit.
Columns: total_votes (candidate/party votes + blank votes blank),
electors (registered, if given), ballots (turnout numerator, if given;
defaults to total_votes at finalize time), bloc_left/right/other and
party_<slug> for every name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
long
|
DataFrame
|
Long table (unit, party, votes). |
required |
blocs
|
Dict[str, dict]
|
Dict from :func: |
required |
unit_col
|
str
|
Unit column. |
'unit'
|
name_col
|
str
|
Party column. |
'party'
|
votes_col
|
str
|
Votes column. |
'votes'
|
blank
|
Optional[Series]
|
Blank votes per unit. |
None
|
electors
|
Optional[Series]
|
Registered electors per unit. |
None
|
ballots
|
Optional[Series]
|
Ballots cast per unit. |
None
|
rejected
|
Optional[Series]
|
Rejected ballots per unit. |
None
|
allocate_pools(counts, unit_group, weights, spread_electors=False)
¶
Spread votes that have no polygon (advance/special/mobile/unlocated polls) over the polygons of the same district.
Rows of counts whose index starts with POOL: (POOL:<group>) are pooled counts of district <group>;
they are split over the real units with unit_group == group proportionally to weights (e.g. registered electors;
uniform if all weights are 0). Registered electors themselves are never redistributed. Mass-conserving per district.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
counts
|
DataFrame
|
Counts per unit, pools included. |
required |
unit_group
|
Series
|
District of each real unit. |
required |
weights
|
Series
|
Weight of each real unit. |
required |
spread_electors
|
bool
|
Also spread the electors. |
False
|
find_worldpop(iso3, worldpop_path=None)
¶
Path of the WorldPop 2025 100 m raster of a country (from the given path, $PYCENSUS_WORLDPOP_DIRS, the default
folders or the cache).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iso3
|
str
|
ISO 3166-1 alpha-3 code. |
required |
worldpop_path
|
Optional[str]
|
Explicit raster path (wins). |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The raster path. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If no raster is found. |
units_to_h3(units, counts, grid, id_col='unit')
¶
Dasymetric (WorldPop-weighted) split of unit counts onto H3 cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
units
|
GeoDataFrame
|
Unit polygons. |
required |
counts
|
DataFrame
|
Counts per unit. |
required |
grid
|
PopulationGrid
|
WorldPop pixels. |
required |
id_col
|
str
|
Unit id column. |
'unit'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Counts per H3 cell. |
h3_to_units(h3_counts, census, grid, id_col='GEOID')
¶
Population-weighted split of H3 counts onto census geometries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h3_counts
|
DataFrame
|
Counts per H3 cell. |
required |
census
|
GeoDataFrame
|
Census polygons. |
required |
grid
|
PopulationGrid
|
WorldPop pixels. |
required |
id_col
|
str
|
Census id column. |
'GEOID'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Counts per census unit. |
kept_parties(counts, min_share=PARTY_MIN_SHARE)
¶
Party columns above min_share of the total votes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
counts
|
DataFrame
|
Counts table. |
required |
min_share
|
float
|
Smallest share kept. |
PARTY_MIN_SHARE
|
Returns:
| Type | Description |
|---|---|
List[str]
|
Column names. |
finalize(counts, scope, year, parties=None)
¶
counts -> elec_<scope>_<year>_* output columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
counts
|
DataFrame
|
Counts table. |
required |
scope
|
str
|
Election scope. |
required |
year
|
int
|
Election year. |
required |
parties
|
Optional[List[str]]
|
Party columns kept. |
None
|
finalize_all(unit_counts, h3_counts, census_counts, scope, year)
¶
Same party list for every geography (selected on the study-area totals).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit_counts
|
DataFrame
|
Counts per unit. |
required |
h3_counts
|
DataFrame
|
Counts per H3 cell. |
required |
census_counts
|
Optional[DataFrame]
|
Counts per census unit (or None). |
required |
scope
|
str
|
Election scope. |
required |
year
|
int
|
Election year. |
required |
Returns:
| Type | Description |
|---|---|
|
|
sanity(frame, scope, year)
¶
Checks of a finished frame: rows, total votes, bloc shares adding to 1, overall left / right shares.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
Output of :func: |
required |
scope
|
str
|
Election scope. |
required |
year
|
int
|
Election year. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dict of the checks. |
schema_features(columns, country, source, native_level, scope_desc)
¶
Schema feature dicts (usa/schema/housing_schema.json format) for election columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
Iterable[str]
|
Election columns. |
required |
country
|
str
|
Country code. |
required |
source
|
str
|
Source name. |
required |
native_level
|
str
|
Geometry the results come at. |
required |
scope_desc
|
Dict[str, str]
|
|
required |
write_schema(path, country, source, full_name, years, levels, features)
¶
Write an election schema JSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Output file. |
required |
country
|
str
|
Country code. |
required |
source
|
str
|
Source name. |
required |
full_name
|
str
|
Source full name. |
required |
years
|
list
|
Election years. |
required |
levels
|
list
|
Geometry levels. |
required |
features
|
list
|
Features from :func: |
required |
run_pipeline(geom, counts, scope, year, iso3, census_geometry, worldpop_path=None, unit_label='unit')
¶
unit counts (+polygons) -> {unit_label, "h3", <census level>...} frames of elec_* columns.
geom: GeoDataFrame(unit, geometry) of the finest result units; counts: build_counts() output (index unit);
census_geometry: level -> GeoDataFrame(GEOID, geometry).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geom
|
GeoDataFrame
|
Unit polygons ( |
required |
counts
|
DataFrame
|
Output of :func: |
required |
scope
|
str
|
Election scope. |
required |
year
|
int
|
Election year. |
required |
iso3
|
str
|
Country ISO3 code (WorldPop). |
required |
census_geometry
|
Dict[str, GeoDataFrame]
|
|
required |
worldpop_path
|
Optional[str]
|
Explicit WorldPop raster. |
None
|
unit_label
|
str
|
Name of the unit level in the output. |
'unit'
|