Skip to content

Instantly share code, notes, and snippets.

@jonblatho

jonblatho/zcta-block.py

Last active Mar 30, 2021
Embed
What would you like to do?
Calculates the population of ZIP Code Tabulation Areas (ZCTAs) which intersect with Howell County, MO
import shapefile
from shapely.geometry import shape
def __shapely_polygon__(s):
return shape(s.shape.__geo_interface__)
# Read Missouri census block shapefile
block_file = shapefile.Reader("block/tabblock2010_29_pophu.shp")
# Obtained from https://www.census.gov/geographies/mapping-files/2010/geo/tiger-data.html
# Read ZIP code tabulation area shapefile
zcta_file = shapefile.Reader("zcta/tl_2019_us_zcta510.shp")
# Obtained from https://www.census.gov/cgi-bin/geo/shapefiles/index.php (select ZIP Code Tabulation Areas)
# Find census blocks in Howell County
howell_blocks = []
for block in block_file.iterShapeRecords():
if block.record[1] == '091':
howell_blocks.append(block)
# Find ZCTA shapes for Howell County ZIP codes
howell_zip_codes = ['65548', '65775', '65793', '65626', '65777', '65788', '65790', '65637', '65789', '65692', '65689', '65609']
howell_zctas = []
for zcta in zcta_file.iterShapeRecords():
if zcta.record[0] in howell_zip_codes:
howell_zctas.append(zcta)
# Create dictionary
dictionary = {}
for zcta in howell_zctas:
dictionary[zcta.record[1]] = {'population': 0, 'bounds': __shapely_polygon__(zcta)}
for block in howell_blocks:
polygon = __shapely_polygon__(block)
for zcta in dictionary:
if dictionary[zcta]["bounds"].overlaps(polygon) or dictionary[zcta]["bounds"].contains(polygon):
dictionary[zcta]["population"] += block.record[7]
break
for zcta in dictionary:
dictionary[zcta].pop("bounds", None)
print(dictionary)
# 65775 West Plains 24554
# 65793 Willow Springs 5414
# 65548 Mountain View 5382
# 65789 Pomona 2030
# 65626 Caulfield 844
# 65790 Pottersville 608
# 65788 Peace Valley 406
# 65692 Koshkonong 349
# 65777 Moody 326
# 65637 Dora 213
# 65609 Bakersfield 191
# 65689 Cabool 83
# ----------------------------
# TOTAL 40400
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment