Load 5-year ACS race + ethnicity data, ending in 2017
This file contains 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
# pip install requests | |
import time, json | |
import requests | |
api_key = "API_KEY_STRING" | |
# look up FIPS for state and county: | |
# https://www.nrcs.usda.gov/wps/portal/nrcs/detail/national/home/?cid=nrcs143_013697 | |
state = '12' | |
county_fips = ['086'] | |
# to load all possible counties in a state: | |
# last_fips = 77 | |
# for fips in range(1, last_fips + 1): | |
# newfips = str(fips) | |
# while len(newfips) < 3: | |
# newfips = '0' + newfips | |
# county_fips.append(newfips) | |
saveblocks = {} | |
for county in county_fips: | |
# race and ethnicity | |
# there is a limit to how many columns you can request! | |
cols = [ | |
'B03002_001E','B03002_003E','B03002_004E','B03002_005E','B03002_006E', | |
'B03002_007E','B03002_008E','B03002_009E','B03002_012E', | |
] | |
name_of = { | |
'B03002_001E': "TOTPOP", | |
'B03002_003E': "NH_WHITE", | |
'B03002_004E': "NH_BLACK", | |
'B03002_005E': "NH_AMIN", | |
'B03002_006E': "NH_ASIAN", | |
'B03002_007E': "NH_NHPI", | |
'B03002_008E': "NH_OTHER", | |
'B03002_009E': "NH_2MORE", | |
'B03002_012E': "HISP", | |
} | |
url = 'https://api.census.gov/data/2018/acs/acs5?get=' + ','.join(cols) + '&for=block group:*&in=state:' + state + '+county:' + county + '&key=' + api_key | |
resp = requests.get(url) | |
blocks = resp.json() | |
print(county + ": " + str(len(blocks))) | |
headers = None | |
for block in blocks: | |
if headers is None: | |
headers = block | |
else: | |
blockid = block[headers.index('state')] + block[headers.index('county')] + block[headers.index('tract')] + block[headers.index('block group')] | |
saveblocks[blockid] = {} | |
for pvar in cols: | |
saveblocks[blockid][name_of[pvar]] = int(block[headers.index(pvar)]) | |
time.sleep(1) | |
open('savefile.json', 'w').write(json.dumps(saveblocks)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment