如何将嵌套JSON格式的API输出转换为pandas DataFrame?
解决嵌套JSON转pandas DataFrame的方案
你遇到的问题是直接用pd.DataFrame()或pd.read_json()无法自动展开嵌套的字典、列表结构,导致数据仍处于嵌套状态。用pd.json_normalize()可以轻松扁平化这类嵌套数据,具体操作如下:
代码实现
import pandas as pd # 定义你的天气数据字典 weather_data = { 'coord': {'lon': 13.4105, 'lat': 52.5244}, 'weather': [{'id': 801, 'main': 'Clouds', 'description': 'few clouds', 'icon': '02d'}], 'base': 'stations', 'main': {'temp': 3.21, 'feels_like': -1.29, 'temp_min': 2.22, 'temp_max': 4.09, 'pressure': 1007, 'humidity': 91}, 'visibility': 10000, 'wind': {'speed': 5.81, 'deg': 119, 'gust': 7.15}, 'clouds': {'all': 20}, 'dt': 1669622280, 'sys': {'type': 2, 'id': 2011538, 'country': 'DE', 'sunrise': 1669618193, 'sunset': 1669647541}, 'timezone': 3600, 'id': 2950159, 'name': 'Berlin', 'cod': 200 } # 扁平化嵌套数据生成DataFrame df = pd.json_normalize(weather_data) # 可选:重命名weather相关列,去掉自动生成的索引前缀 df.rename(columns={ 'weather.0.id': 'weather_id', 'weather.0.main': 'weather_main', 'weather.0.description': 'weather_description', 'weather.0.icon': 'weather_icon' }, inplace=True) # 查看结果 print(df)
关键说明
pd.json_normalize()会自动遍历嵌套的字典(比如coord、main),将其展开为单独列;对于数组类型的字段(比如weather列表),会用字段名.索引.子字段的格式生成列名。- 如果后续处理批量API返回的JSON数组(多个城市的天气数据),直接把数组传入
pd.json_normalize()即可,无需额外循环处理。
内容的提问来源于stack exchange,提问作者Alessia
相关产品推荐
相关产品推荐

