如何将pandas DataFrame转换为字典列表组成的嵌套字典
多层索引DataFrame转指定结构字典实现
需求说明
现有多层索引Pandas DataFrame,结构如下:
end_hour start_hour values level_0 level_1 FRIDAY 0 6 0 {'onDemandTripBase': 4.269,'tripMoving': 1.086,'tripWaiting': 17.375} 1 10 6 {'onDemandTripBase': 4.269,'tripMoving': 1.086,'tripWaiting': 17.375} 2 24 10 {'onDemandTripBase': 4.269,'tripMoving': 1.086,'tripWaiting': 17.375} MONDAY 0 6 0 {'onDemandTripBase': 4.269,'tripMoving': 1.086,'tripWaiting': 17.375} 1 10 6 {'onDemandTripBase': 4.7,'tripMoving': 1.2,'tripWaiting': 19.1} 2 24 10 {'onDemandTripBase': 4.269,'tripMoving': 1.086,'tripWaiting': 17.375}
需转换为如下格式的字典:
{'FRIDAY': [{'end_hour': 6,'start_hour': 0,'values':{'onDemandTripBase':4.269,'tripMoving': 1.086,'tripWaiting': 17.375}}, {'end_hour': 10, 'start_hour': 6, 'values': {'onDemandTripBase': 4.7, 'tripMoving': 1.2, 'tripWaiting': 19.1}}, {'end_hour': 24, 'start_hour': 10, 'values': {'onDemandTripBase': 4.269, 'tripMoving': 1.086, 'tripWaiting': 17.375}}], 'MONDAY': [{'end_hour': 6, 'start_hour': 0, 'values': {'onDemandTripBase': 4.269, 'tripMoving': 1.086, 'tripWaiting': 17.375}}, {'end_hour': 10, 'start_hour': 6, 'values': {'onDemandTripBase': 4.7, 'tripMoving': 1.2, 'tripWaiting': 19.1}}, {'end_hour': 24, 'start_hour': 10, 'values': {'onDemandTripBase': 4.269, 'tripMoving': 1.086, 'tripWaiting': 17.375}}] }
直接使用.to_dict('index')生成的字典键为元组类型,不符合格式要求。
实现代码
# 假设DataFrame变量名为df result = { day: group.droplevel(level=1).to_dict("records") for day, group in df.groupby(level=0) }
逻辑说明
- 调用
groupby(level=0)按多层索引的第一级(FRIDAY、MONDAY等星期标识)拆分数据集 droplevel(level=1)移除第二层数字索引,避免冗余索引字段进入最终结果to_dict("records")将分组内的每一行转换为独立字典,按原行顺序组成列表,完全匹配目标结构
内容的提问来源于stack exchange,提问作者Purushottam Deshpande
相关产品推荐
相关产品推荐

