1

I wrote this code to get specific ACS data for a set of years for all the tracts in Wake County (id 37187) in the state of North Carolina. I've read the census example of how to format the code to get it for certain counties, but haven't been able to figure that out with this implementation. What do I need to put in my predicates["for"] variable to do this?

import requests
import pandas as pd

HOST, dataset = "https://api.census.gov/data", "acs/acs1"

get_vars = ['B25045_001E', 'B25045_001M']
get_vars = ["NAME"] + get_vars

print(get_vars)

predicates = {}
predicates["get"] = ",".join(get_vars)
#not sure how to add to this
predicates["for"] = "state:37"

# initialize data from collector

dfs = []
columns = ["ID", "Estimate", "Estimate_moe", "ID", "Year", "RMOE"]
for year in range(2011, 2018):
    base_url = "/".join([HOST, str(year), dataset])
    r = requests.get(base_url, params=predicates)
    df = pd.DataFrame(columns=r.json()[0], data=r.json()[1:])
    # add column to hold year value
    df["year"] = year
    df['B25045_001M'] = df['B25045_001M'].astype(int)
    df['B25045_001E'] = df['B25045_001E'].astype(int)

    df["RMOE"] = 100 * df['B25045_001M'] / df['B25045_001E']
    dfs.append(df)


nc = pd.concat(dfs)
print(nc.head)
0

2 Answers 2

1

To get the geography you want, you have to specify each level of the geographic hierarchy in which the tracts fit.

state='37'

county='187'

&for=tracts:*&in=county:{county}&in=state:{state}

'For' indicates that you want tracts, the asterisk is a wildcard that says get all of them, in the county you want, in the state you want.

I've got some basic examples here on github if you want to take a look.

1

This is the code that ended up working for me. Also, see https://api.census.gov/data/2017/acs/acs5/examples.html for a large list of formatting examples.

import requests, pandas as pd
year='2018'
dsource='acs'
dname='acs5'
cols='NAME'
state='37'
county='183'
tract='*'

base_url = f'https://api.census.gov/data/{year}/{dsource}/{dname}'


data_url = f'{base_url}?get={cols}&for=tract:*&in=state:{state}&in=county:{county}'

response=requests.get(data_url)

print(response.text)
data=response.json()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.