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

2024-06-16 11:22:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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

如何处理这种期望处理?你知道吗


Tags: 数据代码importapijsoncitydfnan
1条回答
网友
1楼 · 发布于 2024-06-16 11:22:56

使用API中的Response Status code来处理期望值,现在可以正常工作了

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'] 

相关问题 更多 >