我在获取特定州每个城市的人口时遇到问题。我确实得到了城市的人口,但如果我将每个城市的人口相加,我得到的数字与该州的人口不同。
我得到了我的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
我有理由确定“地方”是城市,例如
# 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"]]'
我在做什么错或误解?为什么按地方划分的人口总和不等于该州的人口?