如何在Python中将含列表内字典的JSON数据转换为Pandas DataFrame并筛选指定属性
解决方法:将指定JSON属性转换为Pandas DataFrame
没问题,这就帮你实现把JSON里的指定属性提取成Pandas DataFrame的需求,步骤和代码都给你写清楚:
步骤1:导入必要的库
首先得导入Pandas,这是咱们处理数据框的核心工具:
import pandas as pd
步骤2:定义你的JSON数据
把你提供的JSON数据定义成Python字典(JSON和Python字典格式天然兼容):
json_data = { "name": "Monkey", "image": "https://media.npr.org/assets/img/2017/09/12/macaca_nigra_self-portrait-3e0070aa19a7fe36e802253048411a38f14a79f8-s800-c85.webp", "attributes": [ {"trait_type": "Bones", "value": "Zombie"}, {"trait_type": "Clothes", "value": "Striped"}, {"trait_type": "Mouth", "value": "Bubblegum"}, {"trait_type": "Eyes", "value": "Black Sunglasses"}, {"trait_type": "Hat", "value": "Sushi"}, {"trait_type": "Background", "value": "Purple"} ] }
步骤3:提取指定属性并转换为DataFrame
咱们把attributes里的每个trait_type作为列名,对应的value作为单元格内容。用字典推导式把属性列表转成键值对,再传入Pandas创建DataFrame:
# 从attributes列表中提取键值对,生成字典 attributes_dict = {trait['trait_type']: trait['value'] for trait in json_data['attributes']} # 创建DataFrame(因为是单条数据,要把字典放在列表里) df = pd.DataFrame([attributes_dict]) # 如果需要严格指定列的顺序(和你要求的Bones、Clothes...顺序完全一致),可以加上columns参数 # df = pd.DataFrame([attributes_dict], columns=["Bones", "Clothes", "Mouth", "Eyes", "Hat", "Background"])
步骤4:查看结果
运行上面的代码后,打印df就能得到你想要的DataFrame:
Bones Clothes Mouth Eyes Hat Background 0 Zombie Striped Bubblegum Black Sunglasses Sushi Purple
这样就完美实现了你要的需求——只提取指定的属性作为列,对应的值作为内容的DataFrame。
内容的提问来源于stack exchange,提问作者Zac
相关产品推荐
相关产品推荐

