如何为DataFrame中的API结果按源数据ID分组添加关联ID
解决API结果分组添加对应ID的问题
问题原因
你之前的代码仅在循环结束后保留了最后一个id值,没有为每组内的每个场所重复生成对应ID,导致所有行的ID完全相同。正确的逻辑应该是:为API返回的每个结果组分配一个唯一ID,再将该ID重复对应到组内的所有场所上。
正确实现方案
方法1:直接遍历API数据收集
import pandas as pd # 假设info是你的API返回数据列表 info = [ # 你的API返回的两组数据内容 ] all_places = [] # 遍历每个结果组,从1开始分配ID for group_id, result_group in enumerate(info, start=1): # 遍历组内每个场所,添加对应ID for place in result_group['results']: all_places.append({ 'id': group_id, 'name': place['name'], 'rating': place['rating'], 'location': place['location']['formatted_address'] }) # 生成目标DataFrame df = pd.DataFrame(all_places)
方法2:基于源DataFrame的快速处理(如果已存储API结果)
如果你的源DataFrame已将每组API结果存入某一列(比如api_results),可以用explode快速展开并关联ID:
# 假设source_df是你的源DataFrame,包含api_results列(每个元素为一组场所列表) source_df['id'] = source_df.index + 1 # 生成从1开始的组ID # 展开每个组的场所列表 source_df = source_df.explode('api_results').reset_index(drop=True) # 提取字段生成目标DataFrame df = pd.DataFrame({ 'id': source_df['id'], 'name': source_df['api_results'].apply(lambda x: x['name']), 'rating': source_df['api_results'].apply(lambda x: x['rating']), 'location': source_df['api_results'].apply(lambda x: x['location']['formatted_address']) })
最终效果示例
生成的DataFrame会符合预期的分组ID格式:
| id | 场所 |
|---|---|
| 1 | Leslieville Farmers Market |
| 1 | Rorschach Brewing |
| 2 | Balzac's Coffee Roasters |
| 2 | Rehearsal Factory |
内容的提问来源于stack exchange,提问作者Abdullah G
相关产品推荐
相关产品推荐

