如何将API应用于熊猫数据框

时间:2019-12-20 16:11:44

标签: pandas

我的数据框

uid,api_url
1, abc.com
2, xyz.com

我的json api的密钥url必须从数据帧的api_url中获取并获得响应

  jso ='''{
    "ui_id": "1111",
    "data": {
    "url": "xxxxxxx"
    }
    }'''
    json_d = json.loads(jso)

我的代码

def doc_(response):
    headers = {"Content-Type": "application/json"}
    response = requests.post("abc.com/v3/doc",headers=headers,json=json_d)
    return response.text

要在数据框中创建新列

df['response'] = df['api_url'].apply(doc_)

1 个答案:

答案 0 :(得分:2)

您需要为每个API请求中的每个json_d更新/重新生成api_url
另外,为函数/参数更好地命名。

def query_api(api_url):
    headers = {"Content-Type": "application/json"}
    json_d = {'ui_id': '1111', 'data': {'url': api_url}}
    response = requests.post("http://example.net/v3/doc", 
                             headers=headers, json=json_d)
    return response.text


df['response'] = df['api_url'].apply(query_api)
相关问题