You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Step 1: Install the Required Library

First, you'll need the official googlemaps Python client to interact with the API. Install it via pip:

pip install googlemaps
Step 2: Set Up the Google Maps API Client

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)
Step 3: Create a Helper Function to Fetch Driving Data

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])
Step 4: Apply the Function to Your DataFrame

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
)
Key Tips for Your 10k-Row Dataset
  • 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 Origin and Destination columns 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:29:28