我在让特定州的每个城市的人口问题上遇到了问题。我确实得到了城市的人口,但是如果我将每个城市的人口加起来,我得到的数字将不会与州的人口数相同。

我得到了API Key,将P0010001 variable用于总人口,对马萨诸塞州使用FIPS 25,并向geography level "place"请求人口,我理解这是指城市。

这是我使用的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"]]'

我在做什么错或误解? 为什么按地区划分的人口总数不等于该州的人口总数?

List of example API calls

最佳答案

如果我将每个城市的人口总数相加,则得出的数字与州人口数不同。

这是因为并非每个人都住在城市中-许多县的农村“非法人居住区”不属于任何城市,而且人们确实住在那里。

因此,这不是编程问题!-)

关于python - 美国人口普查API-使用Python获取某个州的每个城市的人口,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28933220/

10-12 19:51