#!/usr/bin/env python # coding: utf-8 # In[5]: import requests import pandas as pd # In[6]: zips = [90049, 60608, 60615] # In[7]: API_URL="http://api.censusreporter.org/1.0/data/show/{release}?table_ids={table_ids}&geo_ids={geoids}" # In[8]: def get_data(tables=None, geoids=None, release='latest'): if geoids is None: geoids = ['040|01000US'] if tables is None: tables = ['B01001'] url = API_URL.format(table_ids=','.join(tables).upper(), geoids=','.join(geoids), release=release) response = requests.get(url) return response.json() # In[22]: def prep_for_pandas(json_data,include_moe=False): """Given a dict of dicts as they come from a Census Reporter API call, set it up to be amenable to pandas.DataFrame.from_dict""" result = {} for geoid, tables in json_data.items(): flat = {} for table,values in tables.items(): for kind, columns in values.items(): if kind == 'estimate': flat.update(columns) elif kind == 'error' and include_moe: renamed = dict((k+"_moe",v) for k,v in columns.items()) flat.update(renamed) result[geoid] = flat return result # In[19]: response = get_data(geoids = ["86000US" + str(z) for z in zips], tables = ['B17001']) df = pd.DataFrame.from_dict(prep_for_pandas(response['data']),orient='index') # In[20]: df # In[21]: df.describe() # In[ ]: