pycensus¶
pyCensus: common-schema census loaders ready to drop into a geohierarchy.GeoHierarchy.
Every source across every country shares two conventions
- Common wording: logical column names (
population,households,gdp, ...) are shared across sources and countries wherever the underlying concept matches, so e.g.populationmeans the same thing whether it came from LODES or the ACS. - Accessors: importing a source module registers a GeoDataFrame
accessor named after it (
gdf.lodes_rac,gdf.acs, ...). Indexing the accessor with a logical column name returns a :class:~pycensus.accessors.ColumnView, which adds.density(value / geometry area in m2, or length in m for lines) and.relative(value / that column's registered total, per :class:~pycensus.schema.ColumnSchema) on top of the raw values.
Each source's loader returns a plain GeoDataFrame with a GEOID id
column and prefixed attribute columns -- pass it straight to
:meth:geohierarchy.GeoHierarchy.add_level (using the source's
SCHEMA.aggregations() for the agg argument) to build a hierarchy,
or use it standalone.
Currently implemented
- United States (:mod:
pycensus.USA): ACS 5-year estimates, 2020 Decennial Census DHC, and LODES RAC/WAC job counts. - Mexico (:mod:
pycensus.mexico): INEGI Census 2020 disaggregated data including population, gender, ethnicity, religion, income, employment, housing, car ownership, and commuting mode. - Spain (:mod:
pycensus.spain): INE Census 2021 disaggregated data including population, nationality, education, income, employment, housing, car ownership, commuting mode, disability, and more. - Israel (:mod:
pycensus.israel): CBS Census 2022 disaggregated data including population, religion, immigration, education, employment, housing. - Germany (:mod:
pycensus.germany): Destatis Census 2022 disaggregated data including population, nationality, education, employment, housing, religion. - Worldwide (:mod:
pycensus.census.worldwide): WorldPop gridded population rasters. - Euskadi (:mod:
pycensus.euskadi): Eustat Census 2021 disaggregated data for the Basque Country, including population, Basque/Spanish language skills, nationality, education, employment, housing, car ownership, and commuting mode.
ColumnView(data, gdf, schema)
¶
Wraps a selected column (or columns) with .density / .relative derivations.
Duck-types the wrapped pandas object by delegating attribute access to
it, so e.g. gdf.lodes["population"].sum() works directly on the
underlying Series without going through .data.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
The selected raw values -- a Series for a single column, a DataFrame for several. |
Initialize the view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[Series, DataFrame]
|
Selected column(s) from |
required |
gdf
|
GeoDataFrame
|
Parent GeoDataFrame, used to compute |
required |
schema
|
ColumnSchema
|
Source's column schema, used to resolve |
required |
ColumnDef(name, codes, relative_to=None, agg='sum', weight_by=None, computed_from=None)
dataclass
¶
A single logical column definition.
agg is the single standard place every part of pyCensus reads to
know whether a column is a count/total or an average/relative
quantity -- nothing else (loaders, .relative, resampling) infers
this independently. Concretely:
"sum"(:attr:is_count): an additive count or total (e.g. population, jobs, households). Its value can be validly summed across rows, and resampling it across geohierarchy levels should reproduce that total exactly (:attr:~geohierarchy.aggregation.AggregationStrategy.preserve_total)."mean"(:attr:is_average): an intensive/relative quantity with no meaningful total (e.g. a median, a rate, a per-capita figure). Resampling it produces a representative value, not a sum, and no total-preservation is expected or attempted.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Common logical name, unprefixed (e.g. |
codes |
List[str]
|
Raw source variable codes summed to build this column. |
relative_to |
Optional[str]
|
Logical name of the column used as the denominator
for |
agg |
Literal['sum', 'mean']
|
|
weight_by |
Optional[str]
|
Logical name of the column used to weight a
|
ColumnSchema(prefix, columns=dict())
dataclass
¶
Registry of a source's logical columns.
Attributes:
| Name | Type | Description |
|---|---|---|
prefix |
str
|
Column name prefix used on the GeoDataFrame and as the
accessor name (e.g. |
columns |
Dict[str, ColumnDef]
|
Mapping of unprefixed logical column name to its
:class: |
add(name, codes, relative_to=None, agg='sum', weight_by=None, computed_from=None)
¶
Register a logical column and return self for chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unprefixed logical column name. |
required |
codes
|
List[str]
|
Raw source variable codes summed to build this column. |
required |
relative_to
|
Optional[str]
|
Unprefixed logical name of the |
None
|
agg
|
Literal['sum', 'mean']
|
|
'sum'
|
weight_by
|
Optional[str]
|
Unprefixed logical name of the weighting column
for |
None
|
computed_from
|
Optional[List[str]]
|
Unprefixed logical names of two other columns
this one is derived from as |
None
|
prefixed(name)
¶
Return the on-GeoDataFrame column name for a logical name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Logical column name. |
required |
Returns:
| Type | Description |
|---|---|
str
|
|
strip_prefix(prefixed_name)
¶
Return the logical (unprefixed) name for an on-GeoDataFrame column name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefixed_name
|
str
|
Column name. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The logical name. |
relative_to(prefixed_name)
¶
Resolve the prefixed denominator column for .relative, if any.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefixed_name
|
str
|
Column name. |
required |
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The denominator column, or None. |
aggregations()
¶
Build a {prefixed_column: AggregationStrategy} map for :meth:geohierarchy.GeoHierarchy.add_level.
Always geoweighted: census geographies (tracts, block groups, H3 cells, ...) rarely nest cleanly, so an un-geoweighted mapping falls back to matching each destination row to whichever single source polygon contains its centroid -- any source row with no destination centroid landing inside it (common for small source polygons matched against much coarser or differently-shaped destination cells) is silently dropped from the result entirely, which can lose the large majority of a column's total. Area-based overlap weighting doesn't have that failure mode.
smooth_aggregations(k=6, power=2.0)
¶
Build a {prefixed_column: AggregationStrategy} map using :class:geohierarchy.SmoothMean downscale.
Same upscale behavior as :meth:aggregations, but every column's
downscale is :class:~geohierarchy.aggregation.SmoothMean instead
of the default geoweighted split -- for a much finer destination
level (e.g. an H3 grid several resolutions past the source data),
where a hard geometric split would look blocky. Each column's
is_count/is_average (from its registered agg) is passed
straight through as SmoothMean(density=...), so count columns
keep their totals exact (:attr:~geohierarchy.aggregation.AggregationStrategy.preserve_total)
while relative/average columns are blended without that constraint
-- exactly the "totals maintained except for relative columns"
rule, applied automatically for every column in this schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of nearest source neighbors to blend per destination row. |
6
|
power
|
float
|
Inverse-distance weighting exponent. |
2.0
|
Returns:
| Type | Description |
|---|---|
Dict[str, 'gh.AggregationStrategy']
|
Mapping suitable for :meth: |
Dict[str, 'gh.AggregationStrategy']
|
(one call per column) or as a per-column override at a specific level. |
resolve_api_key(name, env_var=None, explicit=None)
¶
Return the key for name or None if none is configured.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Key name in |
required |
env_var
|
Optional[str]
|
Environment variable checked first. |
None
|
explicit
|
Optional[str]
|
A key passed directly (wins). |
None
|
Returns:
| Type | Description |
|---|---|
Optional[str]
|
The key, or None. |