API Reference¶
Complete reference for all PyPUMS public functions and classes.
Data Retrieval¶
get_acs¶
pypums.acs.get_acs(geography, variables=None, table=None, state=None, county=None, year=2023, survey='acs5', output='tidy', moe_level=90, summary_var=None, geometry=False, keep_geo_vars=False, cache_table=False, key=None)
¶
Retrieve American Community Survey data from the Census API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geography
|
str
|
Geography level (e.g. |
required |
variables
|
str | list[str] | None
|
Variable ID or list of IDs (e.g. |
None
|
table
|
str | None
|
Census table ID (e.g. |
None
|
state
|
str | None
|
State FIPS code or abbreviation. |
None
|
county
|
str | None
|
County FIPS code. |
None
|
year
|
int
|
Data year (default 2023). |
2023
|
survey
|
str
|
|
'acs5'
|
output
|
str
|
|
'tidy'
|
moe_level
|
int
|
Confidence level for MOE: 90, 95, or 99 (default 90). |
90
|
summary_var
|
str | None
|
Variable ID to include as denominator columns. |
None
|
geometry
|
bool
|
If True, return a GeoDataFrame with shapes. |
False
|
keep_geo_vars
|
bool
|
If True, preserve the raw FIPS columns (state, county, tract, etc.) in the output alongside GEOID. |
False
|
cache_table
|
bool
|
If True, cache the API response locally to avoid redundant calls. |
False
|
key
|
str | None
|
Census API key. Falls back to |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Census data in tidy or wide format. |
get_decennial¶
pypums.decennial.get_decennial(geography, variables=None, table=None, state=None, county=None, year=2020, output='tidy', pop_group=None, geometry=False, keep_geo_vars=False, cache_table=False, key=None)
¶
Retrieve Decennial Census data from the Census API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geography
|
str
|
Geography level (e.g. |
required |
variables
|
str | list[str] | None
|
Variable ID or list of IDs (e.g. |
None
|
table
|
str | None
|
Census table ID. Alternative to variables. |
None
|
state
|
str | None
|
State FIPS code or abbreviation. |
None
|
county
|
str | None
|
County FIPS code. |
None
|
year
|
int
|
Census year: 2000, 2010, or 2020 (default 2020). |
2020
|
output
|
str
|
|
'tidy'
|
pop_group
|
str | None
|
Population group code for DHC-A disaggregated data. |
None
|
geometry
|
bool
|
If True, return a GeoDataFrame with shapes. |
False
|
keep_geo_vars
|
bool
|
If True, preserve the raw FIPS columns (state, county, tract, etc.) in the output alongside GEOID. |
False
|
key
|
str | None
|
Census API key. Falls back to |
None
|
cache_table
|
bool
|
If True, cache the API response locally to avoid redundant calls. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Census data in tidy or wide format. |
get_pums¶
pypums.pums.get_pums(variables=None, *, state=None, puma=None, year=2023, survey='acs5', variables_filter=None, rep_weights=None, recode=False, show_call=False, cache_table=False, key=None)
¶
Load PUMS microdata from the Census API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variables
|
str | list[str] | None
|
PUMS variable name(s) to retrieve (e.g. |
None
|
state
|
str | list[str] | None
|
State abbreviation, name, or FIPS code. Required. |
None
|
puma
|
str | list[str] | None
|
PUMA code(s) to filter by. |
None
|
year
|
int
|
Data year (default 2023). |
2023
|
survey
|
str
|
|
'acs5'
|
variables_filter
|
dict[str, list | int | str] | None
|
Server-side variable filters as |
None
|
rep_weights
|
str | None
|
Include replicate weights: |
None
|
recode
|
bool
|
If True, add |
False
|
show_call
|
bool
|
If True, print the API URL. |
False
|
key
|
str | None
|
Census API key. Falls back to |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Person- or housing-level microdata records. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
get_estimates¶
pypums.estimates.get_estimates(geography, *, product=None, variables=None, breakdown=None, breakdown_labels=False, vintage=2023, year=None, state=None, county=None, time_series=False, output='tidy', geometry=False, cache_table=False, show_call=False, key=None)
¶
Retrieve Population Estimates Program data from the Census API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geography
|
str
|
Geography level (e.g. |
required |
product
|
str | None
|
Estimates product: |
None
|
variables
|
str | list[str] | None
|
Variable ID or list of IDs to request. |
None
|
breakdown
|
str | list[str] | None
|
Breakdown dimensions (e.g. |
None
|
breakdown_labels
|
bool
|
If True, add |
False
|
vintage
|
int
|
Vintage year for the estimates (default 2023). |
2023
|
year
|
int | None
|
Specific data year within the vintage. |
None
|
state
|
str | None
|
State FIPS code or abbreviation. |
None
|
county
|
str | None
|
County FIPS code. |
None
|
time_series
|
bool
|
If True, request data across multiple years within the vintage
by querying the |
False
|
output
|
str
|
|
'tidy'
|
geometry
|
bool
|
If True, return a GeoDataFrame with shapes. |
False
|
cache_table
|
bool
|
If True, cache the API response locally to avoid redundant calls. |
False
|
show_call
|
bool
|
If True, print the API URL. |
False
|
key
|
str | None
|
Census API key. Falls back to |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Population estimates data. |
get_flows¶
pypums.flows.get_flows(geography, *, variables=None, breakdown=None, breakdown_labels=False, year=2019, output='tidy', state=None, county=None, msa=None, geometry=False, moe_level=90, cache_table=False, show_call=False, key=None)
¶
Retrieve ACS Migration Flows data from the Census API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geography
|
str
|
Geography level (e.g. |
required |
variables
|
str | list[str] | None
|
Variable ID or list of IDs to request. |
None
|
breakdown
|
str | list[str] | None
|
Breakdown dimensions for flow characteristics. |
None
|
breakdown_labels
|
bool
|
If True, add |
False
|
year
|
int
|
Data year (default 2019). |
2019
|
output
|
str
|
|
'tidy'
|
state
|
str | None
|
State FIPS code or abbreviation. |
None
|
county
|
str | None
|
County FIPS code. |
None
|
msa
|
str | None
|
Metropolitan Statistical Area code. |
None
|
geometry
|
bool
|
If True, return a GeoDataFrame with shapes for the origin geography. |
False
|
moe_level
|
int
|
Confidence level for MOE: 90, 95, or 99 (default 90). |
90
|
cache_table
|
bool
|
If True, cache the API response locally to avoid redundant calls. |
False
|
show_call
|
bool
|
If True, print the API URL. |
False
|
key
|
str | None
|
Census API key. Falls back to |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Migration flows data with MOVEDIN, MOVEDOUT, MOVEDNET columns. |
Variable Discovery¶
load_variables¶
pypums.variables.load_variables(year, dataset, cache=False)
¶
Load Census variable metadata for a given dataset and year.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
year
|
int
|
Census data year (e.g. 2023). |
required |
dataset
|
str
|
Dataset identifier (e.g. |
required |
cache
|
bool
|
If True, cache the result both in memory and on disk for subsequent calls. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns |
Margins of Error¶
moe_sum¶
pypums.moe.moe_sum(moe)
¶
Calculate the MOE for a derived sum.
Formula: sqrt(sum(moe_i ** 2))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
moe
|
list[float] | Series | ndarray
|
Individual margins of error to combine. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Combined margin of error for the sum. |
moe_ratio¶
pypums.moe.moe_ratio(num, denom, moe_num, moe_denom)
¶
Calculate the MOE for a derived ratio num / denom.
Formula: sqrt(moe_num**2 + (num/denom)**2 * moe_denom**2) / denom
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num
|
float
|
Numerator estimate. |
required |
denom
|
float
|
Denominator estimate. |
required |
moe_num
|
float
|
MOE of the numerator. |
required |
moe_denom
|
float
|
MOE of the denominator. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Margin of error for the ratio. |
moe_prop¶
pypums.moe.moe_prop(num, denom, moe_num, moe_denom)
¶
Calculate the MOE for a derived proportion num / denom.
Formula: sqrt(moe_num**2 - (num/denom)**2 * moe_denom**2) / denom
Falls back to :func:moe_ratio when the radicand is negative
(i.e. when moe_num**2 < p**2 * moe_denom**2).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num
|
float
|
Numerator estimate (subset count). |
required |
denom
|
float
|
Denominator estimate (total count). |
required |
moe_num
|
float
|
MOE of the numerator. |
required |
moe_denom
|
float
|
MOE of the denominator. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Margin of error for the proportion. |
moe_product¶
pypums.moe.moe_product(est1, est2, moe1, moe2)
¶
Calculate the MOE for a derived product est1 * est2.
Formula: sqrt(est1**2 * moe2**2 + est2**2 * moe1**2)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
est1
|
float
|
First estimate. |
required |
est2
|
float
|
Second estimate. |
required |
moe1
|
float
|
MOE of the first estimate. |
required |
moe2
|
float
|
MOE of the second estimate. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Margin of error for the product. |
significance¶
pypums.moe.significance(est1, est2, moe1, moe2, *, clevel=0.9)
¶
Test whether the difference between two estimates is statistically significant.
Converts MOEs (at 90 % confidence) to standard errors, then checks
whether |est1 - est2| exceeds the critical value times the SE
of the difference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
est1
|
float
|
First estimate. |
required |
est2
|
float
|
Second estimate. |
required |
moe1
|
float
|
MOE of the first estimate (at 90 % confidence). |
required |
moe2
|
float
|
MOE of the second estimate (at 90 % confidence). |
required |
clevel
|
float
|
Confidence level for the test: 0.90, 0.95, or 0.99 (default 0.90). |
0.9
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the difference is statistically significant. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If clevel is not one of the supported confidence levels. |
Spatial¶
attach_geometry¶
pypums.spatial.attach_geometry(df, geography, *, state=None, year=2023, resolution='500k', cache=True)
¶
Fetch shapes via pygris and merge with Census tabular data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Census data DataFrame with a |
required |
geography
|
str
|
Geography level name. |
required |
state
|
str | None
|
State FIPS code or abbreviation. |
None
|
year
|
int
|
Data year. |
2023
|
resolution
|
str
|
Shapefile resolution. |
'500k'
|
cache
|
bool
|
If True (default), cache downloaded shapefiles locally. |
True
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
Merged GeoDataFrame with Census data and geometry. |
as_dot_density¶
pypums.spatial.as_dot_density(gdf, values, *, dots_per_value=100, seed=None)
¶
Convert polygon GeoDataFrame to dot-density points.
For each polygon, generates random points proportional to the value in each specified column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
Input GeoDataFrame with polygon geometries. |
required |
values
|
dict[str, str]
|
Mapping of |
required |
dots_per_value
|
int
|
Number of data units per dot (default 100). |
100
|
seed
|
int | None
|
Random seed for reproducibility. |
None
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
Point GeoDataFrame with one row per dot. |
interpolate_pw¶
pypums.spatial.interpolate_pw(from_gdf, to_gdf, *, value_col, weight_col='POP', extensive=True)
¶
Population-weighted areal interpolation.
Transfers values from one set of polygons (from_gdf) to
another (to_gdf) using population weights from a third
layer (the weight column in from_gdf).
This is a simplified implementation that uses overlay intersection areas weighted by population counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
from_gdf
|
GeoDataFrame
|
Source GeoDataFrame with the values to interpolate. |
required |
to_gdf
|
GeoDataFrame
|
Target GeoDataFrame defining the output zones. |
required |
value_col
|
str
|
Column in from_gdf containing the value to interpolate. |
required |
weight_col
|
str
|
Column in from_gdf containing population weights (default |
'POP'
|
extensive
|
bool
|
If True (default), treat as an extensive variable (sum). If False, treat as an intensive variable (weighted average). |
True
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
Copy of to_gdf with an interpolated value column added. |
Survey Design¶
SurveyDesign¶
pypums.survey.SurveyDesign(df, weight, rep_weights, scale=4.0 / 80)
¶
Lightweight survey design object for PUMS data with replicate weights.
Wraps a PUMS DataFrame and its weight/replicate-weight columns to compute weighted estimates and replicate-weight standard errors using the successive differences replication (SDR) method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
PUMS DataFrame (from |
required |
weight
|
str
|
Name of the main weight column (e.g. |
required |
rep_weights
|
list[str]
|
List of replicate weight column names. |
required |
scale
|
float
|
Replicate weight scaling factor (default |
4.0 / 80
|
standard_error(variable)
¶
Compute the replicate-weight standard error for a weighted sum.
Uses the successive-differences replication (SDR) formula:
SE = sqrt(scale * sum((rep_est_r - full_est)^2))
weighted_estimate(variable)
¶
Compute a weighted estimate (sum) for a variable.
weighted_mean(variable)
¶
Compute a weighted mean for a variable.
to_survey¶
pypums.survey.to_survey(df, weight_type='person', design='rep_weights')
¶
Convert a PUMS DataFrame to a weighted survey design object.
Wraps the DataFrame with its weight and replicate weight columns, enabling weighted estimates and standard error computation using successive differences replication.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
PUMS DataFrame (from |
required |
weight_type
|
str
|
Weight type: |
'person'
|
design
|
str
|
Survey design type. Only |
'rep_weights'
|
Returns:
| Type | Description |
|---|---|
SurveyDesign
|
A survey design object with methods for weighted estimation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required weight columns are missing from the DataFrame. |
get_survey_metadata¶
pypums.survey.get_survey_metadata(year=None)
¶
Fetch available Census Bureau dataset metadata.
Queries the Census API discovery endpoint
(https://api.census.gov/data.json) and returns a DataFrame of
available datasets, optionally filtered by year.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
year
|
int | None
|
If provided, filter to datasets for that vintage/year. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns: |
Census Helpers¶
summary_files¶
pypums.census_helpers.summary_files(year=2020)
¶
List available summary files for a given Census year.
Queries the Census API to discover which summary files (datasets) are available for a decennial census year.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
year
|
int
|
Census year (e.g. 2020, 2010). |
2020
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns: |
get_pop_groups¶
pypums.census_helpers.get_pop_groups(year=2020, state=None)
¶
List available population groups for decennial Census DHC-A data.
Population groups are used with the pop_group parameter in
get_decennial() to access disaggregated data by detailed
race/ethnicity categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
year
|
int
|
Census year (default 2020). |
2020
|
state
|
str | None
|
State FIPS code to filter population groups (optional). |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns: |
API Key Management¶
census_api_key¶
pypums.api.key.census_api_key(key=None)
¶
Get or set a Census API key for the current session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str | None
|
If provided, sets this key for the current session via env var. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The active Census API key. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no key is available from any source. |
Geography¶
build_geography_query¶
pypums.api.geography.build_geography_query(geography, state=None, county=None)
¶
Convert geography + state/county to Census API for and in params.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geography
|
str
|
Geography level name (e.g. |
required |
state
|
str | None
|
State FIPS code or name/abbreviation (e.g. |
None
|
county
|
str | None
|
County FIPS code (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[str, str | None]
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the geography is unknown or required parent geographies are missing. |
Caching¶
CensusCache¶
pypums.cache.CensusCache(cache_dir)
¶
Cache Census API responses with optional TTL.
Uses Parquet for DataFrame serialization (safe to deserialize from untrusted sources, unlike pickle).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache_dir
|
Path
|
Directory to store cached files. |
required |
clear()
¶
Remove all cached entries.
get(key)
¶
Retrieve a cached DataFrame, or None if missing/expired.
set(key, df, ttl_seconds=None)
¶
Store a DataFrame in the cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Cache key identifier. |
required |
df
|
DataFrame
|
DataFrame to cache. |
required |
ttl_seconds
|
int | float | None
|
Time-to-live in seconds. |
None
|
FIPS Lookups¶
lookup_fips¶
pypums.datasets.fips.lookup_fips(state=None, county=None)
¶
Look up a FIPS code from a state or county name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
str | None
|
State name (e.g. |
None
|
county
|
str | None
|
County name (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The FIPS code: 2-digit state code, or state+county code. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the state or county is not found. |
lookup_name¶
pypums.datasets.fips.lookup_name(state_code=None, county_code=None)
¶
Look up a state or county name from FIPS code(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_code
|
str | None
|
2-digit state FIPS code (e.g. |
None
|
county_code
|
str | None
|
3-digit county FIPS code (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The state name, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the code is not found. |