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

调用PokeAPI生成的列表转换为DataFrame数据异常该如何解决

问题原因

你当前的result列表中存储的每个元素都是独立的单行DataFrame,直接将这些子DataFrame作为值传入pd.DataFrame()构造函数时,pandas会将完整的子DataFrame作为单个单元格的内容,才会出现每行都附带重复列名的异常结构。

解决方法

直接使用pandas内置的concat()方法拼接列表中所有子DataFrame即可:

# 拼接所有子DataFrame,ignore_index参数用于重置全局行索引
df = pd.concat(result, ignore_index=True)

执行后得到的df就是结构正常的5行标准DataFrame,列保留你提取的id、name、height、weight、base_experience字段。

可选优化方案

如果后续要调整采集逻辑,也可以在采集阶段直接向result中追加字典而不是子DataFrame,后续直接生成DataFrame更节省资源:

result = []
def pokemon(x):
    while x < 5:
        x = x + 1
        url_stat = "https://pokeapi.co/api/v2/pokemon/" + str(x)
        response_stat = requests.get(url_stat)
        poke_data = json.loads(response_stat.text)
        # 直接追加字典
        result.append({
            'id': poke_data['id'],
            'name': poke_data['name'],
            'height': poke_data['height'],
            'weight': poke_data['weight'],
            'base_experience': poke_data['base_experience']
        })
    return result

# 调用后直接生成DataFrame即可
df = pd.DataFrame(pokemon(0))

内容的提问来源于stack exchange,提问作者Agustín

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:57:04