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

如何将API返回的嵌套字典数据转换为Pandas DataFrame?

解决方案

针对你提供的API嵌套字典数据,要生成包含StoreCode、Long、Lat、Bake列的DataFrame,可以通过遍历提取目标字段并整理成结构化数据的方式实现,具体代码如下:

import pandas as pd

# 假设API返回的数据存储在api_data变量中
api_data = {
    'Message': {'Success': True, 'ErrorMessage': ''},
    'StoresAttributes': [
        {'StoreCode': '1004',
         'Categories': [
             {'Code': 'Lctn', 'Attribute': {'Code': 'Long', 'Value': '16.99390523395146'}},
             {'Code': 'Lctn', 'Attribute': {'Code': 'Lat', 'Value': '52.56718450856377'}},
             {'Code': 'Offr', 'Attribute': {'Code': 'Bake', 'Value': 'True'}},
             {'Code': 'Pay', 'Attribute': {'Code': 'SCO', 'Value': 'True'}}
         ]},
        {'StoreCode': '1005',
         'Categories': [
             {'Code': 'Lctn', 'Attribute': {'Code': 'Long', 'Value': '14.2339250'}},
             {'Code': 'Lctn', 'Attribute': {'Code': 'Lat', 'Value': '53.8996090'}},
             {'Code': 'Offr', 'Attribute': {'Code': 'Bake', 'Value': 'True'}},
             {'Code': 'Pay', 'Attribute': {'Code': 'SCO', 'Value': 'True'}},
             {'Code': 'Offr', 'Attribute': {'Code': 'Bchi', 'Value': 'True'}}
         ]}
    ]
}

# 初始化空列表存储门店结构化数据
store_records = []

# 遍历每个门店
for store in api_data['StoresAttributes']:
    record = {'StoreCode': store['StoreCode']}
    # 遍历门店下的所有属性分类
    for cat in store['Categories']:
        attr_code = cat['Attribute']['Code']
        attr_val = cat['Attribute']['Value']
        # 仅提取目标字段
        if attr_code in ['Long', 'Lat', 'Bake']:
            # 转换数据类型:经纬度转浮点型并保留两位小数,Bake转布尔型
            if attr_code in ['Long', 'Lat']:
                record[attr_code] = round(float(attr_val), 2)
            elif attr_code == 'Bake':
                record[attr_code] = attr_val == 'True'
    store_records.append(record)

# 生成DataFrame
result_df = pd.DataFrame(store_records)
print(result_df)

代码说明

  1. 数据提取:先从API返回的字典中取出StoresAttributes列表,这是所有门店数据的集合。
  2. 字段筛选:遍历每个门店,先提取StoreCode,再遍历该门店的Categories列表,筛选出Attribute.Code为Long、Lat、Bake的属性值。
  3. 类型转换:将经纬度的字符串值转为浮点型并保留两位小数,将Bake的字符串"True"转为布尔值True,保证数据格式符合需求。
  4. 生成DataFrame:将整理好的门店字典列表传入pd.DataFrame(),直接生成目标结构的表格。

执行后得到的DataFrame结果如下:

StoreCode   Long    Lat   Bake
0      1004  16.99  52.57   True
1      1005  14.23  53.90   True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 00:31:01