Skip to content

Instantly share code, notes, and snippets.

@mapmeld
Last active July 8, 2020 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mapmeld/bd5fe0f55ea9fbb56a8fb01cb1cdd68e to your computer and use it in GitHub Desktop.
Save mapmeld/bd5fe0f55ea9fbb56a8fb01cb1cdd68e to your computer and use it in GitHub Desktop.
Load 5-year ACS race + ethnicity data, ending in 2017
# 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