用于获取半径内邮政编码的Python脚本无法正确填充CSV

问题描述 投票:0回答:1

我正在尝试编写一个 Python 脚本,该脚本读取包含邮政编码的 CSV 文件,使用 API 获取半径内的邮政编码,然后将结果填充到 CSV 中的新列中。 API 请求似乎工作正常,我可以在控制台输出中看到响应。但是,生成的 CSV 文件的 radius_zips 列中没有预期值。

这是我当前的脚本:

import pandas as pd
import requests

# Define the file paths
input_file_path = 'test_zips.csv'  # Located on the Desktop
output_file_path = 'test_zips_with_radius_zips_output.csv'  # Will be saved on the Desktop

# Define the API details
url = "https://zip-code-distance-radius.p.rapidapi.com/api/zipCodesWithinRadius"
headers = {
    "x-rapidapi-key": "your_api_key",
    "x-rapidapi-host": "zip-code-distance-radius.p.rapidapi.com"
}

# Read the CSV file
df = pd.read_csv(input_file_path)

# Function to get zip codes within a radius for a given zip code
def get_radius_zips(zip_code, radius="10"):
    querystring = {"zipCode": zip_code, "radius": radius}
    try:
        response = requests.get(url, headers=headers, params=querystring)
        response.raise_for_status()
        data = response.json()
        print(f"Response for {zip_code}: {data}")  # Print the full response
        if 'zip_codes' in data:
            zip_codes = [item['zipCode'] for item in data]
            print(f"Zip codes within radius for {zip_code}: {zip_codes}")
            return ', '.join(zip_codes)
        else:
            print(f"No zip codes found for {zip_code}")
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data for zip code {zip_code}: {e}")
    except ValueError as e:
        print(f"Error parsing JSON response for zip code {zip_code}: {e}")
    return ''

# Apply the function to the total_zips column and create the radius_zips column
def process_total_zips(total_zips):
    zip_codes = total_zips.split(', ')
    radius_zip_codes = [get_radius_zips(zip.strip()) for zip in zip_codes]
    radius_zip_codes = [z for z in radius_zip_codes if z]  # Filter out empty strings
    return ', '.join(radius_zip_codes) if radius_zip_codes else ''

df['radius_zips'] = df['total_zips'].apply(process_total_zips)

# Write the modified DataFrame to a new CSV file
df.to_csv(output_file_path, index=False)

print("The new CSV file 'test_zips_with_radius_zips_output.csv' has been created.")

控制台输出表明 API 响应正确:

Response for 01001: [{'zipCode': '01001', 'distance': 0.0}, {'zipCode': '01106', 'distance': 2.9825640831681617}, ...]
Zip codes within radius for 01001: ['01001', '01106', ...]

但是,生成的 CSV 文件仍然有一个空的 radius_zips 列。

以下是输入 CSV 文件 (test_zips.csv) 的示例:

lat,lng,city,state_id,state_name,population,density,shortcode,total_zips
42.06262,-72.62521,Agawam,MA,Massachusetts,16045,548.6,ma_agawam,01001
42.37633,-72.46462,Amherst,MA,Massachusetts,22992,166.7,ma_amherst,01002,01003
...

以下是错误输出 CSV 文件的示例 (test_zips_with_radius_zips_output.csv):

lat,lng,city,state_id,state_name,population,density,shortcode,total_zips,radius_zips
42.06262,-72.62521,Agawam,MA,Massachusetts,16045,548.6,ma_agawam,01001,
42.37633,-72.46462,Amherst,MA,Massachusetts,22992,166.7,ma_amherst,01002,01003,
...

即使 API 响应正确,可能会导致输出 CSV 中的 radius_zips 列为空?

python rest zipcode
1个回答
0
投票

已解决,做了一些代码更改,参见Github https://github.com/hlevenberg/radiuszip

© www.soinside.com 2019 - 2024. All rights reserved.