Python遍历月份列表生成Census API URL遇问题求助
问题:遍历月份列表生成Census API URL时,整个列表被插入而非单个元素
我尝试抓取census.gov的数据,希望通过for循环遍历给定的月份列表来生成符合API语法的请求URL,但打印URL时,显示的是整个月份列表而非单个月份,生成的错误URL如下:https://api.census.gov/data/2023/cps/basic/['may', 'apr', 'mar', 'feb', 'jan']?get=NAME, HEFAMINC &for=county:*&in=state:12
我的代码如下:
# API endpoint and parameters - current pop surveys base_url = 'https://api.census.gov/data' year = '2023' # Latest year of data dataset = 'cps/basic/' # Population and Housing estimates dataset months = ['may', 'apr', 'mar', 'feb', 'jan'], get_variables = 'NAME, HEFAMINC ' # Variables aka the column headers state = '12' # Specify the state code for Florida county = "*" # List to store individual data frames data_frames = [] # Construct the API request URL using an f-string and a for loop to cycle months for 2023 for month in months: url = f'{base_url}/{year}/{dataset}{month}?get={get_variables}&for=county:{county}&in=state:{state}' print(url) # Send the API request response = requests.get(url) # Check if the request was successful, otherwise print error message if response.status_code == 200: # Parse the JSON response data = response.json() # Extract the desired information headers = data[0] # Column headers values = data[1:] # Data values # Create a data frame df = pd.DataFrame(values, columns=headers) # Append the data frame to the list data_frames.append(df) else: print(f'Request failed with status code: {response.status_code}') # Analyze the individual data frames further
解答
问题出在**months变量的定义上:你在列表末尾多写了一个逗号,导致months不是普通列表,而是一个包含单个列表元素的元组**。当你用for month in months循环时,month会被赋值为元组里的整个列表,所以URL中会插入整个列表的字符串表示。
修复步骤:
去掉months定义末尾的逗号,把它变回普通列表:
months = ['may', 'apr', 'mar', 'feb', 'jan'] # 移除末尾的逗号
修改后的完整代码:
# API endpoint and parameters - current pop surveys base_url = 'https://api.census.gov/data' year = '2023' # Latest year of data dataset = 'cps/basic/' # Population and Housing estimates dataset months = ['may', 'apr', 'mar', 'feb', 'jan'] # 修复:移除末尾逗号 get_variables = 'NAME, HEFAMINC ' # Variables aka the column headers state = '12' # Specify the state code for Florida county = "*" # List to store individual data frames data_frames = [] # Construct the API request URL using an f-string and a for loop to cycle months for 2023 for month in months: url = f'{base_url}/{year}/{dataset}{month}?get={get_variables}&for=county:{county}&in=state:{state}' print(url) # 现在会打印每个月份对应的正确URL # Send the API request response = requests.get(url) # Check if the request was successful, otherwise print error message if response.status_code == 200: # Parse the JSON response data = response.json() # Extract the desired information headers = data[0] # Column headers values = data[1:] # Data values # Create a data frame df = pd.DataFrame(values, columns=headers) # Append the data frame to the list data_frames.append(df) else: print(f'Request failed with status code: {response.status_code}') # Analyze the individual data frames further
效果说明:
修改后,for month in months会遍历列表中的每个字符串元素('may'、'apr'等),生成的URL会正确插入单个月份,例如:https://api.census.gov/data/2023/cps/basic/may?get=NAME, HEFAMINC &for=county:*&in=state:12
内容的提问来源于stack exchange,提问作者labratchet
相关产品推荐
相关产品推荐

