Compare income across ZIP territories and years in Python

Compare genuine IRS reported income across fictional ZIP territories in 2018 and 2023, retaining unavailable comparisons and source limitations.

Compare reported income across ZIP territories

A business has customer or service ZIP codes and wants to see how the surrounding income picture has changed. IRS annual tax-return statistics provide one view: reported adjusted gross income (AGI), numbers of returns, and income-class detail. This example compares mean reported AGI per return in 2018 and 2023 for three territories.

input.csv contains three fictional territory assignments, A, B and C, using real ZIP codes. The same records appear in the territories list in the Python code below. The territory assignments illustrate a business’s input; the IRS income figures are genuine.

Download zip_history.csv below. It is a small version of the paid profile table: all six annual records for ZIPs 01001, 27513 and 27601, with every field unchanged. The input CSV is optional because its records are also in the code. The full $29 edition adds all published ZIPs, income classes, annual definitions, disclosure flags, coverage and reviewed comparisons. Inspect the complete download.

This is tax-return income, not median household income or an estimate of customer spending. If you only need 2023, the single-year reference contains overlapping 2023 coverage; you do not need both products.

Code example

Place the sample in your working directory and run this code in a notebook, IPython or a script. It uses Python’s standard library, keeps ZIP codes as text and reads the file one row at a time. Mean AGI equals published AGI in thousands of dollars × 1,000 ÷ published returns. The change uses the unrounded ratios.

Paths are relative to your working folder; use from pathlib import Path; print(Path.cwd()) to check it, or supply full paths.

Python 3.10+ · Jupyter, IPython or a script
"""Compare nominal reported income across fictional service territories."""
import csv
from decimal import Decimal, ROUND_HALF_UP

# The optional input.csv contains this identical fictional territory list.
territories = [
    {'territory_id': 'A', 'zip_code': '01001'},
    {'territory_id': 'B', 'zip_code': '27513'},
    {'territory_id': 'C', 'zip_code': '27601'},
]
reference_file = 'zip_history.csv'
start_year, end_year = '2018', '2023'


def compare_income(inputs, filename, start, end):
    requested = {r['zip_code'] for r in inputs}
    rows = {}
    with open(filename, newline='', encoding='utf-8') as stream:
        for row in csv.DictReader(stream):
            key = (row['zip_code'], row['tax_year'])
            if key[0] not in requested or key[1] not in {start, end}:
                continue
            if row['geography_status'] != 'postal_zip' or key in rows:
                raise ValueError('Unexpected aggregate or duplicate ZIP/year')
            rows[key] = row
    results = []
    for item in inputs:
        a, b = rows.get((item['zip_code'], start)), rows.get((item['zip_code'], end))
        result = {**item, 'start_mean_agi_usd': '', 'end_mean_agi_usd': '',
                  'percent_change': '', 'status': 'missing_year'}
        if a and b:
            result['status'] = 'unavailable_value'
            if all(r['agi_thousands_usd'] and r['returns'] and Decimal(r['returns']) > 0 for r in (a, b)):
                first = Decimal(a['agi_thousands_usd']) * 1000 / Decimal(a['returns'])
                last = Decimal(b['agi_thousands_usd']) * 1000 / Decimal(b['returns'])
                result.update(start_mean_agi_usd=str(first.quantize(Decimal('1'), rounding=ROUND_HALF_UP)),
                              end_mean_agi_usd=str(last.quantize(Decimal('1'), rounding=ROUND_HALF_UP)))
                result['status'] = 'state_label_changed' if a['state_fips'] != b['state_fips'] else 'nonpositive_baseline' if first <= 0 else 'available'
                if result['status'] == 'available':
                    result['percent_change'] = str(((last / first - 1) * 100).quantize(Decimal('.01'), rounding=ROUND_HALF_UP))
        results.append(result)
    return results


results = compare_income(territories, reference_file, start_year, end_year)
print(f'Mean reported AGI per return, {start_year}–{end_year} (nominal dollars)')
print('ZIP       Start        End      Change')
for row in results:
    if row['status'] != 'available':
        print(f"{row['zip_code']}  {row['status']}")
    else:
        print(f"{row['zip_code']}  ${int(row['start_mean_agi_usd']):>9,}  "
              f"${int(row['end_mean_agi_usd']):>9,}  {row['percent_change']:>7}%")

Analysis of the output

Mean reported AGI per return, 2018–2023 (nominal dollars)
ZIP       Start        End      Change
01001  $   60,019  $   75,731    26.18%
27513  $  124,235  $  154,729    24.55%
27601  $   73,950  $  104,517    41.33%

In the sample, mean reported AGI per return changes from $60,019 to $75,731 for 01001, 26.18% in nominal terms. ZIPs 27513 and 27601 show 24.55% and 41.33%, respectively. Those differences are descriptive, not evidence about the same taxpayers or a business’s customers.

The comparison gives a business a way to place its own territory results beside changes in reported local income. Look at both the number of returns and mean AGI: a change in the filer population can accompany a change in the mean. Neither measure demonstrates that existing customers became wealthier.

The displayed dollar amounts are nominal. Inflation, tax-law changes, filer composition and geographic changes can all affect the interpretation. This calculation does not measure real purchasing power, disposable income, median household income or demand for a business’s product.

The original return counts are rounded to tens. ACD derives mean AGI from those published counts and amounts, so the result has that limitation. It is a mean across included returns, not a survey estimate of every household or resident.

Using the full dataset

Extract your purchase and replace the sample with the full zip_history.csv; the code runs unchanged. Change start_year and end_year to another pair from 2018–2023. Replace territories with your own records read using csv.DictReader, keeping territory_id and zip_code or adapting their names. ZIP+4 inputs can explicitly be reduced to the first five digits; this product does not estimate ZIP+4 statistics.

period_changes.csv supplies comparisons for 2018–2023, 2019–2023 and 2022–2023. Each measure retains both endpoints and a comparison status. Missing years, unavailable values, nonpositive baselines and state-label changes are identified. A blank comparison is not zero change. The code similarly keeps unavailable territory comparisons in its output.

zip_coverage.csv lists the years actually present for each ZIP. annual_coverage.csv reports coverage by state and year. The original source combines some small or nonresidential ZIPs into code 99999; those aggregates and state totals are supplied in separate files, not treated as geographic ZIPs.

Use zip_totals.csv for all original measures from the separate all-income totals. Each zip_income_brackets_YYYY.csv contains that year’s six income classes. Do not add total rows to class rows, or expect rounded or combined class values to sum exactly to the published total.

The state workbooks display some cells as **, which numeric CSVs alone cannot reliably represent. ACD restores those flags: marked cells are blank and listed in disclosure_fields. An unmarked source zero is preserved but does not prove an underlying absence. Fields not published in an edition are separately listed in not_in_source_fields.

Some older CSV and workbook values disagree. Their analytic cells remain blank and appear in source_conflict_fields; source_conflicts.csv supplies both numbers for review. Nonintegral 2021 farm-return counts are also blank and retained for review, even where both originals agree on a fractional value. Original workbook dots are separately unavailable. Two 2018 Oregon ZIPs omitted from the CSVs are retained from the workbook with an explicit source status.

Read measures.csv by tax year and source field. The 2018 source combines IRA and pension income; later editions separate them. The wage source reference changes to Form 1040 line 1z in 2022, so automatic wage comparisons crossing that boundary are withheld. Pandemic payment and credit codes can change meaning between years. edition_notes.csv and the six original guide texts preserve these details and source-document inconsistencies.

Each reference CSV fits within Excel’s worksheet row limit. Import through Data > From Text/CSV and set ZIP columns to text before loading. Files with all original measures are wide; start with the smaller profile table when its selected fields answer your question.

Tax-return addresses need not be residence addresses, and the population excludes nonfilers and negative-AGI returns. An unchanged ZIP code does not establish constant boundaries or the same people. Compare with ZIP business history or Census household-income distributions only after reviewing periods, geography and population differences. Compare ZIP and geography products.

Sources and versions

The IRS SOI ZIP Code series supplies the six annual editions free. ACD retained their CSVs, state workbooks, guides and source pages on November 29, 2026 UTC. Tax years describe observation coverage; source processing periods, capture date and ACD processing revision are separate facts. Exact original release dates were not established.

This is a fixed collection of the annual files available at capture, not an archive of every version originally published. ACD adds documented CSVs, original-source reconciliation, recovered disclosure flags, annual definitions, coverage and tested examples. Read the source and preparation record.

Processing improvements and genuine publisher-error corrections to the purchased edition are included. New periods and routine revisions may be separate paid editions. There is no subscription or membership in future publications.

Example checked November 29, 2026 against both these samples and the complete purchased files. Source and processing records, sample checksums · Expected result CSV. Independent preparation; no agency endorsement.