Add ZIP-level tax-filer income context in Python
Join fictional service territories to genuine IRS ZIP return counts, income totals and calculated mean AGI per return.
Add income context to service territories
A business has customer or service-area ZIP codes and wants to compare the income reported by tax filers in each area. The IRS ZIP profile adds return counts, adjusted gross income and a calculated mean AGI per return, without assembling state spreadsheets or mistaking a suppressed value for zero.
input.csv contains a fictional list of service territories. The identical records appear in the territories list in the Python code below. These inputs illustrate a leading-zero ZIP, a ZIP+4 reduced to five digits, and an aggregate code that should not match a customer territory. The IRS reference values are genuine.
Download zip_profile.csv below and save it in your working directory. This is a genuine subset of the paid file: the complete 41-field profiles for ZIPs 01001, 27513 and 27601. The optional input CSV is also supplied inline in the code.
The full $29 edition provides 27,689 ZIP profiles, all 163 source measures in separate total and income-class tables, disclosure flags and field definitions across nine reference CSVs. Inspect the complete ZIP income and tax dataset.
Code example
Use this code in a notebook, IPython or a Python script; it requires only the standard library. The reference has one profile per published geographic ZIP, so the join adds context without multiplying territory rows. ZIPs remain text and unmatched inputs remain in the output.
Paths are relative to your working folder; use from pathlib import Path; print(Path.cwd()) to check it, or supply full paths.
"""Add published IRS tax-filer income context to fictional service territories."""
import csv
import re
# The optional input.csv contains this identical fictional service-territory list.
territories = [
{'territory_id': 'T01', 'postal_zip': '01001'},
{'territory_id': 'T02', 'postal_zip': '27513-1234'},
{'territory_id': 'T03', 'postal_zip': '27601'},
{'territory_id': 'T04', 'postal_zip': '00000'},
]
reference_file = 'zip_profile.csv'
def normalize_zip(value):
value = value.strip()
if not value:
return '', 'missing_input'
if re.fullmatch(r'[0-9]{5}', value):
return value, 'zip5'
if re.fullmatch(r'[0-9]{9}|[0-9]{5}-[0-9]{4}', value):
return value[:5], 'zip_plus4_to_zip5'
return '', 'invalid_format'
def add_income_context(inputs, filename):
requested = {normalize_zip(r['postal_zip'])[0] for r in inputs}
reference = {}
with open(filename, newline='', encoding='utf-8') as stream:
for row in csv.DictReader(stream):
if row['zip_code'] not in requested:
continue
if row['tax_year'] != '2023' or row['geography_status'] != 'postal_zip' or row['zip_code'] in {'00000', '99999'}:
raise ValueError('Unexpected edition or aggregate in ZIP profile')
if row['zip_code'] in reference:
raise ValueError('Ambiguous ZIP reference')
reference[row['zip_code']] = row
results = []
for item in inputs:
zip5, method = normalize_zip(item['postal_zip'])
row = reference.get(zip5)
status = ('matched' if row else method if not zip5 else
'aggregate_code_not_customer_zip' if zip5 in {'00000','99999'} else
'not_in_published_zip_reference')
results.append({**item, 'zip5': zip5, 'normalization_method': method,
'match_status': status, 'state_abbr': row['state_abbr'] if row else '',
'returns': row['returns'] if row else '',
'agi_thousands_usd': row['agi_thousands_usd'] if row else '',
'mean_agi_per_return_usd': row['mean_agi_per_return_usd'] if row else ''})
return results
results = add_income_context(territories, reference_file)
print('Tax year 2023: published ZIP tax-filer context')
print('ZIP State Returns AGI ($ thousands) Mean AGI per return ($)')
for row in results:
if row['match_status'] != 'matched':
print(f"{row['zip5']:<6} {row['match_status']}")
continue
print(f"{row['zip5']:<6} {row['state_abbr']:<5} {int(row['returns']):>7,} "
f"{int(row['agi_thousands_usd']):>20,} {int(row['mean_agi_per_return_usd']):>24,}")
print('Mean AGI uses rounded return counts; it is not median household income.')
Analysis of the output
Tax year 2023: published ZIP tax-filer context
ZIP State Returns AGI ($ thousands) Mean AGI per return ($)
01001 MA 9,020 683,092 75,731
27513 NC 22,630 3,501,522 154,729
27601 NC 4,050 423,292 104,517
00000 aggregate_code_not_customer_zip
Mean AGI uses rounded return counts; it is not median household income.
For ZIP 27513, the IRS reports 22,630 returns and $3,501,522 thousand in adjusted gross income for tax year 2023. Dividing the published amount by the rounded return count gives about $154,729 per return. The corresponding means are $75,731 in 01001 and $104,517 in 27601. These fields let an analyst compare tax-filer income context across territories alongside their own sales or service records.
This is mean AGI per tax return, not median household income. Joint returns, nonfilers, excluded negative-AGI returns and source disclosure rules affect the population represented. The mean can be influenced by high incomes. It does not describe an individual customer, and a return’s mailing address may differ from the filer’s residence. The displayed whole-dollar result is a calculation from rounded and disclosure-affected source inputs, not that level of measurement precision.
The ZIP+4 input becomes 27513 with a labeled normalization method; no statistics for its last four digits are supplied. The 00000 input is retained as an aggregate code, not joined to the state total. An ordinary ZIP missing from the reference would remain unmatched, which does not mean zero income or no residents.
Using the full dataset
After purchase, extract the archive and replace the sample with the complete zip_profile.csv. The example runs unchanged. Replace territories with rows from your own CSV, using csv.DictReader and preserving ZIPs as text.
zip_totals.csv retains all 163 original IRS measures, decoded by measures.csv. zip_income_brackets.csv supplies six income classes per ZIP; select a class before a many-to-one join or keep the detail deliberately. The separately published all-income totals are not calculated by adding brackets. IRS can combine items across classes, round counts or exclude values, so bracket sums need not match a total.
Source workbook ** markings become numeric blanks with the affected field codes listed in disclosure_fields. The profile gives each selected measure its own status. Unmarked zeros stay zero but are not proof of no underlying activity. The download retains and labels 14 all-zero workbook rows absent from the bulk CSV; it does not create a result for an unpublished ZIP. State totals and other-ZIP aggregates are in separate files.
No companion purchase is required. For population, housing or median household income, consider the ACS ZIP-area profile, whose ZCTA geography and 2020–2024 survey period differ from these postal-ZIP tax records. The ZIP business reference supplies employer establishment counts by industry. Each describes a different population; matching codes does not make their denominators interchangeable. Compare the ZIP-area products.
Sources and versions
The free original source is IRS Statistics of Income, 2023 ZIP Code Data. Tax year 2023 is based on returns processed during calendar 2024, with the source-defined inclusion of earlier returns as a late-filing proxy. ACD captured both bulk CSVs, all 51 state workbooks and the original guide on November 22, 2026. The source listing did not establish an original publication date.
Preparation preserves original ZIP identifiers, uses published totals, restores workbook disclosure formats omitted from the bulk CSV, and supplies separate source and processing identities. A second reader checks every delivered reference-table field against the retained original files. Read the source and preparation record.
This is a fixed source edition. Processing improvements and genuine publisher-error corrections to the purchased edition are included; later source editions may be sold separately. Independent preparation by Actually Clean Data does not imply IRS endorsement.
Example checked November 22, 2026 against both these samples and the complete purchased files. Source and processing records, sample checksums · Expected result CSV. Independent preparation; no agency endorsement.