如何从嵌套字典创建指定格式的多层索引pandas DataFrame
实现代码
import pandas as pd # 此处替换为你自己的嵌套字典 raw_dict = { 0: { "geometry": { "type": "Point", "coordinates": [75.4516454, 27.2520587] }, "type": "Feature", "properties": { "state": "Rajasthan", "code": "BDHL", "name": "Badhal", "zone": "NWR", "address": "Kishangarh Renwal, Rajasthan" } } } # 提取行数据与对应索引 processed_rows = [] row_index = [] for key, val in raw_dict.items(): row_index.append(key) processed_rows.append([ val["geometry"]["type"], val["geometry"]["coordinates"], val["type"], val["properties"]["state"], val["properties"]["code"], val["properties"]["name"], val["properties"]["zone"], val["properties"]["address"] ]) # 构造双层列索引 multi_col = pd.MultiIndex.from_tuples([ ("Geometry", "Type"), ("Geometry", "Coordinates"), ("Type", ""), ("Properties", "State"), ("Properties", "Code"), ("Properties", "Name"), ("Properties", "Zone"), ("Properties", "Address") ]) # 生成目标DataFrame target_df = pd.DataFrame(processed_rows, index=row_index, columns=multi_col) # 打印验证结果 print(target_df)
关键说明
- 遍历原始嵌套字典时直接收集第一层键作为行索引列表,传入DataFrame的
index参数即可保留原始键作为行主索引 - 用
pd.MultiIndex.from_tuples定义双层列的层级关系,无二级子列的顶层列(如示例中的Type)二级索引设为空字符串即可 - 若原始数据存在字段缺失,可在遍历取值时增加判断逻辑补入默认值,避免报错
内容的提问来源于stack exchange,提问作者saransh agarkar
相关产品推荐
相关产品推荐

