如何将DataFrame行作为查询参数通过requests.post发送给API并关联返回结果
实现方案
根据你使用的API是否支持批量查询,有两种常用实现方式:
方案1:API支持批量提交(优先选择,效率更高)
如果API的input参数支持传入句子列表,可直接批量查询,仅需一次请求即可拿到所有结果:
- 先构造ID与句子的映射关系,同时生成批量查询参数
import pandas as pd import requests # 先完成登录步骤,拿到有效headers api_response = requests.post("https://api.com/login", json=login_request) headers = {"Authorization": "你的token"} # 按实际返回的鉴权信息填写 # 构造ID和句子的映射表,用于后续关联结果 id_sentence_map = df.set_index('Column_Sentence')['Column_ID'].to_dict() # 生成批量查询参数 search_query = {'input': df['Column_Sentence'].tolist()} # 发起批量请求 api_response = requests.post("https://api.com/login/sentence_semantic", json=search_query, headers=headers) batch_results = api_response.json()
- 关联返回结果与原df行
如果API返回结果的顺序和你传入句子的顺序完全一致,直接按索引匹配即可:
final_result = [] for idx, top10_res in enumerate(batch_results): final_result.append({ "Column_ID": df.iloc[idx]['Column_ID'], "Column_Sentence": df.iloc[idx]['Column_Sentence'], "top10_similar_sentences": top10_res }) # 也可以直接转成DataFrame存储 result_df = pd.DataFrame(final_result)
如果返回结果顺序不确定,可通过返回结果里携带的输入句子字段匹配id_sentence_map拿到对应ID即可。
方案2:API仅支持单条句子提交
如果API一次只能处理一个句子,遍历df逐行发起请求,直接绑定ID即可:
import pandas as pd import requests # 完成登录拿到有效headers api_response = requests.post("https://api.com/login", json=login_request) headers = {"Authorization": "你的token"} final_result = [] for _, row in df.iterrows(): current_id = row['Column_ID'] current_sentence = row['Column_Sentence'] # 构造单条查询参数 search_query = {'input': current_sentence} api_response = requests.post("https://api.com/login/sentence_semantic", json=search_query, headers=headers) top10_res = api_response.json() final_result.append({ "Column_ID": current_id, "Column_Sentence": current_sentence, "top10_similar_sentences": top10_res }) result_df = pd.DataFrame(final_result)
注意事项
如果数据量较大,单条遍历请求效率较低,可使用concurrent.futures.ThreadPoolExecutor发起异步请求,注意控制并发数避免触发API限流规则。
内容的提问来源于stack exchange,提问作者AHK
相关产品推荐
相关产品推荐

