Skip to content

openavmkit.utilities.census

US Census API integration.

Wraps the census library to fetch ACS demographic and income data for parcel locations, joining Census block-group geometries spatially with the parcel universe. Requires a US Census API key — see the configuration docs for setup. Activated via data.process.enrich.census in settings.json.

CensusCredentials

CensusCredentials(api_key)

Object for storing US Census API credentials

Attributes:

Name Type Description
api_key str

API Key for the US Census

Initialize a CensusCredentials object

api_key : str API Key for the US Census

Source code in openavmkit/utilities/census.py
28
29
30
31
32
33
34
def __init__(self, api_key: str):
    """Initialize a CensusCredentials object

    api_key : str
        API Key for the US Census
    """
    self.api_key = api_key

CensusService

CensusService(credentials)

Provides functions for downloading data from the US Census

Attributes:

Name Type Description
credentials CensusCredentials

Credentials for the US Census

census_client Census

US Census API Client object

Initialize the CensusService object

Parameters:

Name Type Description Default
credentials CensusCredentials

Credentials for the US Census

required
Source code in openavmkit/utilities/census.py
49
50
51
52
53
54
55
56
57
58
def __init__(self, credentials: CensusCredentials):
    """Initialize the CensusService object

    Parameters
    ----------
    credentials : CensusCredentials
        Credentials for the US Census
    """
    self.credentials = credentials
    self.census_client = Census(credentials.api_key)

get_census_blockgroups_shapefile

get_census_blockgroups_shapefile(fips_code)

Get Census Block Group shapefiles for a given FIPS code from the Census TIGERweb service.

Parameters:

Name Type Description Default
fips_code str

5-digit FIPS code (state + county)

required

Returns:

Type Description
GeoDataFrame

GeoDataFrame containing Census Block Group boundaries

Raises:

Type Description
TypeError

If fips_code is not a string

ValueError

If fips_code is not 5 digits

RequestException

If API request fails

Source code in openavmkit/utilities/census.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def get_census_blockgroups_shapefile(self, fips_code: str) -> gpd.GeoDataFrame:
    """Get Census Block Group shapefiles for a given FIPS code from the Census TIGERweb service.

    Parameters
    ----------
    fips_code : str
        5-digit FIPS code (state + county)

    Returns
    -------
    gpd.GeoDataFrame
        GeoDataFrame containing Census Block Group boundaries

    Raises
    ------
    TypeError
        If fips_code is not a string
    ValueError
        If fips_code is not 5 digits
    requests.RequestException
        If API request fails
    """
    if not isinstance(fips_code, str):
        raise TypeError("fips_code must be a string")
    if len(fips_code) != 5:
        raise ValueError("fips_code must be 5 digits (state + county)")

    # TIGERweb REST API endpoint for block groups
    base_url = "https://tigerweb.geo.census.gov/arcgis/rest/services/TIGERweb/Tracts_Blocks/MapServer/1/query"

    # Query parameters
    params = {
        "where": f"STATE='{fips_code[:2]}' AND COUNTY='{fips_code[2:]}'",
        "outFields": "*",
        "returnGeometry": "true",
        "f": "geojson",
        "outSR": "4326",  # WGS84
    }

    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()
        geojson_data = response.json()

        # Convert to GeoDataFrame
        gdf = gpd.GeoDataFrame.from_features(geojson_data["features"])

        # Create standardized GEOID components
        gdf["state_fips"] = gdf["STATE"]
        gdf["county_fips"] = gdf["COUNTY"]
        gdf["tract_fips"] = gdf["TRACT"]
        gdf["bg_fips"] = gdf["BLKGRP"]

        # Create standardized GEOID
        gdf["std_geoid"] = (
            gdf["state_fips"]
            + gdf["county_fips"]
            + gdf["tract_fips"]
            + gdf["bg_fips"]
        )

        # Explicitly set the CRS to EPSG:4326 (WGS84)
        gdf.crs = "EPSG:4326"

        return gdf

    except requests.RequestException as e:
        raise requests.RequestException(
            f"Failed to fetch Census Block Group data: {str(e)}"
        )

get_census_data

get_census_data(fips_code, year=2022, census_settings=None)

Get Census demographic data for block groups in a given FIPS code.

Parameters:

Name Type Description Default
fips_code str

5-digit FIPS code (state + county)

required
year int

Census year to query (default: 2022)

2022
census_settings dict

Census settings

None

Returns:

Type Description
DataFrame

DataFrame containing Census demographic data

Raises:

Type Description
TypeError

If fips_code is not a string or year is not an int

ValueError

If fips_code is not 5 digits

Source code in openavmkit/utilities/census.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def get_census_data(
    self, 
    fips_code: str, 
    year: int = 2022,
    census_settings: dict = None
) -> pd.DataFrame:
    """Get Census demographic data for block groups in a given FIPS code.

    Parameters
    ----------
    fips_code : str
        5-digit FIPS code (state + county)
    year : int
        Census year to query (default: 2022)
    census_settings : dict
        Census settings

    Returns
    -------
    pd.DataFrame
        DataFrame containing Census demographic data

    Raises
    ------
    TypeError
        If fips_code is not a string or year is not an int
    ValueError
        If fips_code is not 5 digits
    """
    if not isinstance(fips_code, str):
        raise TypeError("fips_code must be a string")
    if not isinstance(year, int):
        raise TypeError("year must be an integer")
    if len(fips_code) != 5:
        raise ValueError("fips_code must be 5 digits (state + county)")

    # Split FIPS code into state and county
    state_fips = fips_code[:2]
    county_fips = fips_code[2:]

    map = self.get_census_map(census_settings)
    fields = ["NAME"] + [key for key in map]

    # Get block group data
    data = self.census_client.acs5.state_county_blockgroup(
        fields,
        state_fips=state_fips,
        county_fips=county_fips,
        blockgroup="*",  # All block groups
        year=year,
    )

    # Convert to DataFrame
    df = pd.DataFrame(data)

    # Rename columns
    df = df.rename(
        columns=map
    )

    # Create GEOID for block groups (state+county+tract+block group)
    df["state_fips"] = df["state"]
    df["county_fips"] = df["county"]
    df["tract_fips"] = df["tract"]
    df["bg_fips"] = df["block group"]

    # Create standardized GEOID
    df["std_geoid"] = (
        df["state_fips"] + df["county_fips"] + df["tract_fips"] + df["bg_fips"]
    )

    return df

get_census_data_with_boundaries

get_census_data_with_boundaries(fips_code, year=2022, census_settings=None)

Get both Census demographic data and boundary files for block groups in a FIPS code.

Parameters:

Name Type Description Default
fips_code str

5-digit FIPS code (state + county)

required
year int

Census year to query (default: 2022)

2022
census_settings dict

Census settings object

None

Returns:

Type Description
Tuple[pd.DataFrame, gpd.GeoDataFrame]:
  • Census demographic data DataFrame
  • Census Block Group boundaries GeoDataFrame

Raises:

Type Description
TypeError

If inputs have wrong types

ValueError

If inputs have invalid values

RequestException

If API requests fail

Source code in openavmkit/utilities/census.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
def get_census_data_with_boundaries(
    self, fips_code: str, year: int = 2022, census_settings : dict = None
) -> Tuple[pd.DataFrame, gpd.GeoDataFrame]:
    """Get both Census demographic data and boundary files for block groups in a
    FIPS code.

    Parameters
    ----------
    fips_code :str
        5-digit FIPS code (state + county)
    year : int
        Census year to query (default: 2022)
    census_settings : dict
        Census settings object
    Returns
    -------
    Tuple[pd.DataFrame, gpd.GeoDataFrame]:

        - Census demographic data DataFrame
        - Census Block Group boundaries GeoDataFrame

    Raises
    ------
    TypeError
        If inputs have wrong types
    ValueError
        If inputs have invalid values
    requests.RequestException
        If API requests fail
    """
    # Get demographic data first
    census_data = self.get_census_data(fips_code, year, census_settings)
    census_data = null_jam_values(census_data, list(self.get_census_map(census_settings).values()))
    if (census_settings or {}).get("tract_fallback", False):
        # A block group's figure the ACS withholds: its tract's, where the tract has one.
        tracts = self.get_census_tract_data(fips_code, year, census_settings)
        census_data = fill_from_tracts(
            census_data, tracts, list(self.get_census_map(census_settings).values())
        )
    # Get the list of block groups we have data for
    valid_block_groups = census_data["std_geoid"].unique()

    # Get boundary files
    census_boundaries = self.get_census_blockgroups_shapefile(fips_code)
    # Filter boundaries to only include block groups we have data for
    census_boundaries = census_boundaries[
        census_boundaries["std_geoid"].isin(valid_block_groups)
    ]

    # Merge demographic data with boundaries
    census_boundaries = census_boundaries.merge(
        census_data, on="std_geoid", how="left"
    )
    # Verify the merge
    missing_geoids = census_boundaries[census_boundaries.isna().any(axis=1)][
        "std_geoid"
    ].unique()
    if len(missing_geoids) > 0:
        print(
            f"\nWarning: Found {len(missing_geoids)} block groups with missing data"
        )
        print("First few missing GEOIDs:", missing_geoids[:5])

    return census_data, census_boundaries

get_census_tract_data

get_census_tract_data(fips_code, year=2022, census_settings=None)

The same figures as get_census_data, for the county's tracts (a tract is a few block groups), keyed by the 11-digit tract GEOID (tract_geoid). The ACS publishes a tract's figure where a block group's is withheld (too few households of the kind to estimate it), so it stands in for the block group's.

Source code in openavmkit/utilities/census.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def get_census_tract_data(
    self, fips_code: str, year: int = 2022, census_settings: dict = None
) -> pd.DataFrame:
    """The same figures as get_census_data, for the county's tracts (a tract is a few block groups), keyed by the
    11-digit tract GEOID (``tract_geoid``). The ACS publishes a tract's figure where a block group's is withheld
    (too few households of the kind to estimate it), so it stands in for the block group's."""
    map = self.get_census_map(census_settings)
    fields = ["NAME"] + [key for key in map]
    data = self.census_client.acs5.state_county_tract(
        fields,
        state_fips=fips_code[:2],
        county_fips=fips_code[2:],
        tract="*",
        year=year,
    )
    df = pd.DataFrame(data).rename(columns=map)
    df["tract_geoid"] = df["state"] + df["county"] + df["tract"]
    return null_jam_values(df, list(map.values()))

fill_from_tracts

fill_from_tracts(bg, tracts, columns)

Each block group's missing figure from its tract (the first 11 digits of its GEOID), where the tract has one. bg needs std_geoid; tracts needs tract_geoid.

Source code in openavmkit/utilities/census.py
318
319
320
321
322
323
324
325
326
327
328
329
def fill_from_tracts(
    bg: pd.DataFrame, tracts: pd.DataFrame, columns: list[str]
) -> pd.DataFrame:
    """Each block group's missing figure from its tract (the first 11 digits of its GEOID), where the tract has
    one. ``bg`` needs ``std_geoid``; ``tracts`` needs ``tract_geoid``."""
    bg = bg.copy()
    by_tract = tracts.set_index("tract_geoid")
    tract_of = bg["std_geoid"].astype(str).str[:11]
    for col in columns:
        if col in bg.columns and col in by_tract.columns:
            bg[col] = bg[col].fillna(tract_of.map(by_tract[col]))
    return bg

get_creds_from_env_census

get_creds_from_env_census()

Get Census credentials from environment variables.

Returns:

Type Description
CensusCredentials

Census API credentials

Raises:

Type Description
ValueError

If required environment variables are missing

Source code in openavmkit/utilities/census.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
def get_creds_from_env_census() -> CensusCredentials:
    """Get Census credentials from environment variables.

    Returns
    -------
    CensusCredentials
        Census API credentials

    Raises
    ------
    ValueError
        If required environment variables are missing
    """
    api_key = os.getenv("CENSUS_API_KEY")
    if not api_key:
        warnings.warn("Missing Census API key in environment.")
        return None
    return CensusCredentials(api_key)

init_service_census

init_service_census(credentials)

Initialize a Census service with the provided credentials.

Parameters:

Name Type Description Default
credentials CensusCredentials

Census API credentials

required

Returns:

Type Description
CensusService

Initialized Census service

Raises:

Type Description
ValueError

If credentials are invalid

Source code in openavmkit/utilities/census.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
def init_service_census(credentials: CensusCredentials) -> CensusService:
    """Initialize a Census service with the provided credentials.

    Parameters
    ----------
    credentials : CensusCredentials
        Census API credentials

    Returns
    -------
    CensusService
        Initialized Census service

    Raises
    ------
    ValueError
        If credentials are invalid
    """
    if not isinstance(credentials, CensusCredentials):
        raise ValueError("Invalid credentials for Census service.")
    return CensusService(credentials)

match_to_census_blockgroups

match_to_census_blockgroups(gdf, census_gdf, join_type='left', nearest_m=0.0)

Match each row in a GeoDataFrame to its corresponding Census Block Group using spatial join.

Parameters:

Name Type Description Default
gdf GeoDataFrame

Input GeoDataFrame to match

required
census_gdf GeoDataFrame

Census Block Group boundaries GeoDataFrame

required
join_type str

Type of join to perform ('left', 'right', 'inner', 'outer')

'left'
nearest_m float

A parcel whose centroid is in no block group (a gap or sliver between their shapes, or just past the county's edge) takes the nearest block group within this many meters. 0 (the default): it stays unmatched.

0.0

Returns:

Type Description
GeoDataFrame

Input GeoDataFrame with Census Block Group data appended

Source code in openavmkit/utilities/census.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def match_to_census_blockgroups(
    gdf: gpd.GeoDataFrame,
    census_gdf: gpd.GeoDataFrame,
    join_type: str = "left",
    nearest_m: float = 0.0,
) -> gpd.GeoDataFrame:
    """Match each row in a GeoDataFrame to its corresponding Census Block Group using
    spatial join.

    Parameters
    ----------
    gdf : gpd.GeoDataFrame
        Input GeoDataFrame to match
    census_gdf : gpd.GeoDataFrame
        Census Block Group boundaries GeoDataFrame
    join_type : str
        Type of join to perform ('left', 'right', 'inner', 'outer')
    nearest_m : float
        A parcel whose centroid is in no block group (a gap or sliver between their shapes, or just past the
        county's edge) takes the nearest block group within this many meters. 0 (the default): it stays unmatched.

    Returns
    -------
    gpd.GeoDataFrame
        Input GeoDataFrame with Census Block Group data appended
    """
    if not isinstance(gdf, gpd.GeoDataFrame):
        raise TypeError("gdf must be a GeoDataFrame")
    if not isinstance(census_gdf, gpd.GeoDataFrame):
        raise TypeError("census_gdf must be a GeoDataFrame")
    if join_type not in ["left", "right", "inner", "outer"]:
        raise ValueError("join_type must be one of: 'left', 'right', 'inner', 'outer'")

    # Create a copy of the input GeoDataFrame to avoid modifying the original
    gdf_for_join = gdf.copy()

    if "geometry" not in gdf_for_join:
        raise ValueError("Input dataframe must have a 'geometry' column!")

    # If the data is in a geographic CRS (like WGS84/EPSG:4326),
    # reproject to a projected CRS before calculating centroids
    if gdf_for_join.crs.is_geographic:
        # Use the geometry utility to get an appropriate equal-area CRS based on the data
        projected_crs = get_crs(gdf_for_join, "equal_area")
        gdf_for_join = gdf_for_join.to_crs(projected_crs)
        census_gdf = census_gdf.to_crs(projected_crs)

    # Calculate centroids in the projected CRS
    gdf_for_join["centroid"] = gdf_for_join.geometry.centroid

    # Create a temporary GeoDataFrame with centroids for the spatial join
    centroid_gdf = gpd.GeoDataFrame(
        gdf_for_join.drop(columns=["geometry"]),
        geometry="centroid",
        crs=gdf_for_join.crs,
    )

    # Perform the spatial join
    census_gdf = census_gdf.to_crs(centroid_gdf.crs)

    # Measure the BLOCK GROUP polygons before the join. After it, `joined` carries the
    # left frame's geometry -- the centroid points -- whose area is always 0.0, so a
    # tie-break computed there degenerates to "whichever row the join happened to
    # emit first".
    census_gdf = census_gdf.copy()
    census_gdf["_census_area"] = census_gdf.geometry.area

    joined = centroid_gdf.sjoin(census_gdf, predicate="intersects", how=join_type)
    if "index_right" in joined:
        joined = joined.drop(columns="index_right")

    # If we have matches, process them
    if not joined.empty:
        # A centroid sitting on a shared boundary intersects more than one block
        # group; keep the smallest polygon, which is the tightest containing unit.
        #
        # The join emits one row per (parcel, block group) match, so a boundary
        # parcel appears more than once under the SAME index label. idxmin returns
        # index *labels*, and .loc on a duplicated label pulls back every row that
        # shares it -- which would defeat the whole de-duplication. Reset to a unique
        # positional index first, group by the original label, and select on that.
        # Unmatched rows (left join, no block group) carry a NaN area, which would
        # make idxmin yield NaN for their group, so push them to +inf: they are alone
        # in their group and must still be selected.
        orig_index = joined.index
        joined = joined.reset_index(drop=True)
        areas = joined["_census_area"].fillna(float("inf"))
        smallest_areas = areas.groupby(orig_index.to_numpy()).idxmin()
        joined = joined.loc[smallest_areas]
        joined.index = pd.Index(smallest_areas.index, name=orig_index.name)
        joined = joined.drop(columns="_census_area")

        if nearest_m > 0 and joined["std_geoid"].isna().any():
            # Centroids in no block group: the nearest one, if it's close (a gap between shapes, not another
            # county). The polygons are in a projected crs here, so the distance is in its units (meters).
            lost = joined["std_geoid"].isna()
            near = gpd.sjoin_nearest(
                joined.loc[lost, ["centroid"]].set_geometry("centroid"),
                census_gdf.drop(columns="_census_area"),
                how="left",
                max_distance=nearest_m,
            )
            near = near[~near.index.duplicated(keep="first")]
            for col in census_gdf.columns:
                if col in ("geometry", "_census_area") or col not in near.columns:
                    continue
                joined.loc[lost, col] = near[col].reindex(joined.index[lost]).values

        # Calculate and print percentage of records with valid census geoid
        valid_geoid_count = joined["std_geoid"].notna().sum()
        valid_percentage = (valid_geoid_count / len(gdf)) * 100
        print(
            f"Census block group matching: {valid_geoid_count} of {len(gdf)} records have valid census geoid ({valid_percentage:.2f}%)"
        )

        # restore the original geometry column
        joined = joined.merge(gdf[["key","geometry"]], on="key", how="left")
        joined = joined.set_geometry("geometry")
        joined = joined.drop(columns=["centroid"])

        return joined
    else:
        # No matches, so just return the original GeoDataFrame with census columns added (all NaN)
        census_columns = ["std_geoid", "median_income", "total_pop"]
        for col in census_columns:
            if col in census_gdf.columns:
                gdf[col] = None

        print(f"Census block group matching: 0 of {len(gdf)} records matched (0.00%)")
        return gdf

null_jam_values

null_jam_values(df, columns)

The ACS's codes for a figure it doesn't give (every large negative value) as missing, in these columns.

Source code in openavmkit/utilities/census.py
308
309
310
311
312
313
314
315
def null_jam_values(df: pd.DataFrame, columns: list[str]) -> pd.DataFrame:
    """The ACS's codes for a figure it doesn't give (every large negative value) as missing, in these columns."""
    df = df.copy()
    for col in columns:
        if col in df.columns:
            values = pd.to_numeric(df[col], errors="coerce")
            df[col] = values.mask(values <= ACS_JAM_BELOW)
    return df