我遇到了一个问题,无法获取特定州每个城市的人口数量。我可以获取每个城市的人口数量,但如果将每个城市的人口总和起来,得到的结果与该州的人口总数不同。
我使用了API密钥并使用了P0010001变量作为总人口数,在请求马萨诸塞州(FIPS 25)所在的州的人口时,按地理级别“地方”获取人口,这意味着城市。
以下是我使用的Python 3代码:
我做错了什么或者有什么误解?为什么按地点统计的人口总和不等于州的人口总数? 示例API调用列表
我使用了API密钥并使用了P0010001变量作为总人口数,在请求马萨诸塞州(FIPS 25)所在的州的人口时,按地理级别“地方”获取人口,这意味着城市。
以下是我使用的Python 3代码:
import urllib.request
import ast
class Census:
def __init__(self, key):
self.key = key
def get(self, fields, geo, year=2010, dataset='sf1'):
fields = [','.join(fields)]
base_url = 'http://api.census.gov/data/%s/%s?key=%s&get=' % (str(year), dataset, self.key)
query = fields
for item in geo:
query.append(item)
add_url = '&'.join(query)
url = base_url + add_url
print(url)
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
return response.read()
c = Census('<mykey>')
state = c.get(['P0010001'], ['for=state:25'])
# url: http://api.census.gov/data/2010/sf1?key=<mykey>&get=P0010001&for=state:25
county = c.get(['P0010001'], ['in=state:25', 'for=county:*'])
# url: http://api.census.gov/data/2010/sf1?key=<mykey>&get=P0010001&in=state:25&for=county:*
city = c.get(['P0010001'], ['in=state:25', 'for=place:*'])
# url: http://api.census.gov/data/2010/sf1?key=<mykey>&get=P0010001&in=state:25&for=place:*
# Cast result to list type
state_result = ast.literal_eval(state.decode('utf8'))
county_result = ast.literal_eval(county.decode('utf8'))
city_result = ast.literal_eval(city.decode('utf8'))
def count_pop_county():
count = 0
for item in county_result[1:]:
count += int(item[0])
return count
def count_pop_city():
count = 0
for item in city_result[1:]:
count += int(item[0])
return count
以下是结果:
print(state)
# b'[["P0010001","state"],\n["6547629","25"]]'
print('Total state population:', state_result[1][0])
# Total state population: 6547629
print('Population in all counties', count_pop_county())
# Population in all counties 6547629
print('Population in all cities', count_pop_city())
# Population in all cities 4615402
我相当确定“place”指的是城市,例如:
# Get population of Boston (FIPS is 07000)
boston = c.get(['P0010001'], ['in=state:25', 'for=place:07000'])
print(boston)
# b'[["P0010001","state","place"],\n["617594","25","07000"]]'
我做错了什么或者有什么误解?为什么按地点统计的人口总和不等于州的人口总数? 示例API调用列表