Last active
January 31, 2016 19:04
-
-
Save danhammer/6b281a8bc0492bb7d1ae to your computer and use it in GitHub Desktop.
Converts a street address to a census tract number, based on current Census benchmark and vintage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import urllib | |
def census_tract(street_address, city, state): | |
""" | |
Accepts an address -- split into street number, city, and state -- and | |
returns the census tract number as a string. | |
Example: | |
census_tract("2301 N Brazosport Blvd", "Freeport", "TX") | |
>>> '664300' | |
""" | |
base = "http://geocoding.geo.census.gov/geocoder/geographies/address" | |
# The benchmark is the time period when Census created a snapshot of the | |
# data (generally done twice a year). Public_AR_Current is the most recent | |
# snapshot. The vintage of geography is the census or survey that the data | |
# relates to. For example, Census2010_Census2010 are the address ranges | |
# from the 2010 Census at the time of the 2010 Census. We use the most | |
# recent vintage. | |
payload = dict( | |
street=street_address, | |
city=city, | |
state=state, | |
benchmark="Public_AR_Current", | |
vintage="Current_Current", | |
format="json" | |
) | |
r = requests.get(base + "?" + urllib.urlencode(payload)) | |
data = r.json() | |
match = data['result']['addressMatches'] | |
if not match: | |
return None | |
else: | |
# returns the result from the (zero-indexed) best match | |
tracts = match[0]['geographies']['Census Tracts'] | |
return tracts[0]['TRACT'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment