首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何从Google的distance API的json响应中提取值并存储到python dataframe中?

要从Google的Distance Matrix API的JSON响应中提取值并存储到Python DataFrame中,你需要先获取API的响应,然后解析这个响应,并将其转换为DataFrame。以下是详细的步骤和示例代码:

步骤 1: 获取API响应

首先,你需要使用Google Distance Matrix API来获取距离和持续时间的数据。这通常涉及到发送一个HTTP请求并接收JSON格式的响应。

步骤 2: 解析JSON响应

使用Python的json模块来解析API返回的JSON数据。

步骤 3: 创建DataFrame

使用pandas库来创建一个DataFrame,并将解析后的数据填充进去。

示例代码

代码语言:txt
复制
import requests
import pandas as pd
import json

# 假设你已经有了Google Distance Matrix API的URL和你的API密钥
api_url = "https://maps.googleapis.com/maps/api/distancematrix/json"
api_key = "YOUR_API_KEY"

# 设置请求参数
params = {
    "origins": "Seattle,WA",
    "destinations": "San+Francisco,CA",
    "key": api_key
}

# 发送请求并获取响应
response = requests.get(api_url, params=params)
data = response.json()

# 解析JSON响应
try:
    # 提取距离和持续时间
    distances = data['rows'][0]['elements'][0]['distance']['text']
    durations = data['rows'][0]['elements'][0]['duration']['text']
    
    # 创建DataFrame
    df = pd.DataFrame({
        'Origin': ['Seattle,WA'],
        'Destination': ['San Francisco,CA'],
        'Distance': [distances],
        'Duration': [durations]
    })
    
    print(df)
except KeyError as e:
    print(f"KeyError: {e}. The structure of the JSON response might have changed.")
except Exception as e:
    print(f"An error occurred: {e}")

注意事项

  • 确保你的API密钥是有效的,并且你有权限使用Distance Matrix API。
  • 根据你的需求调整originsdestinations参数。
  • 错误处理是必要的,因为API响应的结构可能会变化,或者可能出现网络请求失败等情况。

参考链接

  • Google Distance Matrix API文档: https://developers.google.com/maps/documentation/distance-matrix/start
  • pandas DataFrame文档: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html

请确保在实际应用中处理好API请求的频率限制和成本问题。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

  • 领券