<s> import pandas as pd <EOL> import requests <EOL> API_URL = "<STR_LIT>" <EOL> def get_data ( tables = None , geoids = None , release = '<STR_LIT>' ) : <EOL> if geoids is None : <EOL> geoids = [ '<STR_LIT>' ] <EOL> elif isinstance ( geoids , basestring ) : <EOL> geoids = [ geoids ] <EOL> if tables is None : <EOL> tables = [ '<STR_LIT>' ] <EOL> elif isinstance ( tables , basestring ) : <EOL> tables = [ tables ] <EOL> url = API_URL . format ( table_ids = '<STR_LIT:U+002C>' . join ( tables ) . upper ( ) , <EOL> geoids = '<STR_LIT:U+002C>' . join ( geoids ) , <EOL> release = release ) <EOL> response = requests . get ( url ) <EOL> return response . json ( ) <EOL> def get_dataframe ( tables = None , geoids = None , release = '<STR_LIT>' , geo_names = False , col_names = False , include_moe = False ) : <EOL> response = get_data ( tables = tables , geoids = geoids , release = release ) <EOL> frame = pd . DataFrame . from_dict ( prep_for_pandas ( response [ '<STR_LIT:data>' ] , include_moe ) , orient = '<STR_LIT:index>' ) <EOL> frame = frame [ sorted ( frame . columns . values ) ] <EOL> if geo_names : <EOL> geo = pd . DataFrame . from_dict ( response [ '<STR_LIT>' ] , orient = '<STR_LIT:index>' ) <EOL> frame . insert ( <NUM_LIT:0> , '<STR_LIT:name>' , geo [ '<STR_LIT:name>' ] ) <EOL> if col_names : <EOL> d = { } <EOL> for table_id in response [ '<STR_LIT>' ] : <EOL> columns = response [ '<STR_LIT>' ] [ table_id ] [ '<STR_LIT>' ] <EOL> for column_id in columns : <EOL> d [ column_id ] = columns [ column_id ] [ '<STR_LIT:name>' ] <EOL> frame = frame . rename ( columns = d ) <EOL> return frame <EOL> def prep_for_pandas ( json_data , include_moe = False ) : <EOL> """<STR_LIT>""" <EOL> result = { } <EOL> for geoid , tables in json_data . items ( ) : <EOL> flat = { } <EOL> for table , values in tables . items ( ) : <EOL> for kind , columns in values . items ( ) : <EOL> if kind == '<STR_LIT>' : <EOL> flat . update ( columns ) <EOL> elif kind == '<STR_LIT:error>' and include_moe : <EOL> renamed = dict ( ( k + "<STR_LIT>" , v ) for k , v in columns . items ( ) ) <EOL> flat . update ( renamed ) <EOL> result [ geoid ] = flat <EOL> return result <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> df = get_dataframe ( ) <EOL> print "<STR_LIT>" <EOL> print df . sort ( '<STR_LIT>' , ascending = False ) [ '<STR_LIT>' ] . head ( <NUM_LIT:10> ) </s>
