gpt4 book ai didi

python - 从 API 将数据写入数据帧时失败

转载 作者:行者123 更新时间:2023-12-01 06:53:28 25 4
gpt4 key购买 nike

我有一个 API,可以向其传递特定值并从 Python 检索特定值。

我正在对 API 进行迭代调用并获取值并将其存储到数据帧。

**Perfect Working  Format Passing Values to API**
cities = ['BUSAN','SACHEON','SINGAPORE','RIO GRANDE','GUANGZHOU']

但是在我的真实数据场景中,我有无效值,我没有从 API 响应。我该如何应对期望

cities = ['BUSAN','XCBZ','999BB','GUANGZHOU'] 

API 失败并显示如下消息

{"message": "The browser (or proxy) sent a request that this server could not understand."}\n'

我的代码

当只有正确的值时,此代码可以完美运行,但当 API 无法找到值时,此代码会失败

import pandas as pd
import json
import requests
cities = ['BUSAN','XWY','999','GUANGZHOU']
df_results = pd.DataFrame( list(zip( cities)), columns =[ 'City'])
results ={}
df_results["lat"] = ""
df_results["lon"] = ""

for i, row in df_results.iterrows():
d_ = "{{ \"address\" : \"{0}\" }}".format(str(row["City"]))
response = requests.post('https://example.com', headers=headers, params=params, data=d_)
d = json.loads(response.text)
df_results["lat"].iloc[i]=d['position']['lat']
df_results["lon"].iloc[i]=d['position']['lon']

我的预期产出

City       lat   lon
BUSAN 1.234 10.234
XWY NaN NaN
999 NaN NaN
GUANGZHOU 1.345 8.456

如何处理这种期望处理?

最佳答案

使用 API 中的响应状态代码来处理异常,现在工作正常

results ={}
df_results["lat"] = ""
df_results["lon"] = ""
for i, row in df_results.iterrows():
d_ = "{{ \"address\" : \"{0}\" }}".format(str(row["City"]))
response = requests.post('https://example.com/geocoder/geocode', headers=headers, params=params, data=d_)
if (response.status_code)!=200:
#print("Error: Unexpected response {}".format(response))
df_results["lat"].iloc[i]="NA"
df_results["lon"].iloc[i]="NA"
elif (response.status_code)==200:
d = json.loads(response.text)
df_results["lat"].iloc[i]=d['position']['lat']
df_results["lon"].iloc[i]=d['position']['lon']

关于python - 从 API 将数据写入数据帧时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58902044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com