Python结合Google Maps API计算DataFrame中起终点的驾车距离与耗时
Hey there! Let's walk through how to calculate driving distances and travel times between your origin and destination addresses using the Google Maps API with your pandas DataFrame. Here's a practical, step-by-step solution tailored for your 10k-row dataset:
First, you'll need the official googlemaps Python client to interact with the API. Install it via pip:
pip install googlemaps
Before you start, make sure you have a valid Google Maps API key (you can get one from the Google Cloud Console) and that the Distance Matrix API is enabled for your project. Then initialize the client:
import googlemaps import pandas as pd import time # Replace with your actual API key API_KEY = "YOUR_GOOGLE_MAPS_API_KEY" gmaps = googlemaps.Client(key=API_KEY)
This function will take an origin and destination address, call the Distance Matrix API, extract the driving distance and duration, and handle any errors (like invalid addresses or API limits):
def get_driving_details(origin, destination): try: # Add a small delay to avoid hitting API rate limits (critical for 10k rows!) time.sleep(0.1) # Request driving route data response = gmaps.distance_matrix( origins=origin, destinations=destination, mode="driving" ) # Extract distance (convert meters to kilometers) and duration (seconds to minutes) element = response["rows"][0]["elements"][0] distance_km = element["distance"]["value"] / 1000 duration_min = element["duration"]["value"] / 60 return pd.Series([distance_km, duration_min]) except Exception as e: # Log errors and return NaN values for problematic rows print(f"Failed to process {origin} → {destination}: {str(e)}") return pd.Series([None, None])
Use pandas' apply method to run the helper function on every row, adding two new columns for distance and duration:
# Add new columns to your DataFrame df[["Driving_Distance_KM", "Driving_Duration_Min"]] = df.apply( lambda row: get_driving_details(row["Origin"], row["Destination"]), axis=1 )
- API Quota Check: The Google Maps Distance Matrix API has usage limits (free tier includes 1,000 requests/month). For 10k rows, you'll need to either upgrade to a paid plan or batch your requests over multiple billing cycles.
- Rate Limits: Even with a paid plan, Google enforces per-second request limits. The
time.sleep(0.1)in the helper function helps avoid hitting these limits—adjust the delay if you still get rate-limit errors. - Address Quality: Ensure your
OriginandDestinationcolumns contain full, valid addresses (e.g., "123 Main St, New York, NY 10001") to maximize API accuracy. Partial addresses might lead to missing or incorrect data.
内容的提问来源于stack exchange,提问作者user9745401

