English 中文(简体)
在半径内获取 zip 代码的 Python 脚本无法正确弹出 CSV 正确
原标题:Python script to fetch zip codes within a radius fails to populate CSV correctly
I am trying to write a Python script that reads a CSV file with zip codes, fetches zip codes within a radius using an API, and then populates the results into a new column in the CSV. The API requests seem to be working correctly, and I can see the responses in the console output. However, the resulting CSV file does not have the expected values in the radius_zips column. Here is my current script: 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.") The console output indicates that the API responses are correct: Response for 01001: [{ zipCode : 01001 , distance : 0.0}, { zipCode : 01106 , distance : 2.9825640831681617}, ...] Zip codes within radius for 01001: [ 01001 , 01106 , ...] However, the resulting CSV file still has an empty radius_zips column. Here is a sample of the input CSV file (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 ... Here is a sample of the incorrect output CSV file (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, ... What could be causing the radius_zips column to be empty in the output CSV, even though the API responses are correct?
问题回答
Solved, made several code changes, see Github https://github.com/hlevenberg/radiuszip




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签