如何合并通过Rest API获取的多个Pandas DataFrame?
问题描述
我正在调用Rest API,需要将返回数据转换为DataFrame格式,采用Pandas库实现。由于API查询参数关联数据库,会得到多个API输出结果,希望将这些输出合并为同一个DataFrame。以下是我的代码及当前输出结果,请求帮助:
我的代码
cur.execute("SELECT * from curd") rows = cur.fetchall() l = [] for row in rows: #print("ID = ", row[1], "\n") r = requests.get("http://localhost:8280/ID="+row[1], headers={uniquestr('Authorization'): 'Basic ',uniquestr('Authorization'): 'Basic'}) #print("CONSUMER_ID = ", row[1], "\n") s = r.json() df = pd.DataFrame(s['R']['L']) df1 = df.groupby(pd.to_datetime(df.DateTime).dt.date).agg({'ACT': 'sum'}).reset_index()
当前输出
DateTime ACT_IMP_TOT 0 2022-05-01 19.252 1 2022-05-02 19.911 2 2022-05-03 23.671 DateTime ACT_IMP_TOT 0 2022-05-01 37.352 1 2022-05-02 27.780 2 2022-05-03 28.557
解决方案
你当前的核心问题是每次循环生成的df1没有被收集存储,最终无法合并。按以下方式修改代码即可解决:
- 初始化一个空列表,用于存放每个API返回处理后的DataFrame
- 每次循环将处理好的
df1添加到该列表中 - 循环结束后,使用
pd.concat()合并所有DataFrame,若需合并相同日期的统计值,可再次按日期分组求和
修改后的代码
import pandas as pd import requests cur.execute("SELECT * from curd") rows = cur.fetchall() df_collection = [] # 存储每个API处理后的DataFrame for row in rows: # 修正headers:字典重复键会被覆盖,需传入正确的Authorization头 api_url = f"http://localhost:8280/ID={row[1]}" headers = {'Authorization': 'Basic <你的Base64编码认证信息>'} r = requests.get(api_url, headers=headers) s = r.json() df = pd.DataFrame(s['R']['L']) # 处理日期并聚合 df1 = df.groupby(pd.to_datetime(df.DateTime).dt.date).agg({'ACT': 'sum'}).reset_index() df_collection.append(df1) # 将当前结果加入列表 # 合并所有DataFrame merged_df = pd.concat(df_collection, ignore_index=True) # 若需合并相同日期的总和,执行以下步骤 final_df = merged_df.groupby('DateTime').agg({'ACT': 'sum'}).reset_index() print(final_df)
关键注意事项
- 原代码中
headers的写法错误:字典内重复的键会被覆盖,需提供正确的单个Authorization头,将<你的Base64编码认证信息>替换为实际的账号密码Base64编码值。 - 如果不同API返回的相同日期数据需要累加,必须在合并后再次执行
groupby求和;若仅需纵向拼接所有结果,可跳过最后一步的groupby操作。
内容的提问来源于stack exchange,提问作者riya
相关产品推荐
相关产品推荐

