You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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场所
1Leslieville Farmers Market
1Rorschach Brewing
2Balzac's Coffee Roasters
2Rehearsal Factory

内容的提问来源于stack exchange,提问作者Abdullah G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 00:46:09