【发布时间】:2021-07-21 13:49:03
【问题描述】:
我有一个看起来像这样的 Pandas 数据框:
Parent_id Child_id Descr
1 2 Tom
1 3 Mark
1 4 Tony
2 5 Eddy
2 6 Lisa
3 7 Anna
3 8 Maria
7 9 Ali
Desired Output 是这样的嵌套 list-dict 组合格式(我需要将它作为 JSON 传递给树视图构建器)。 我不知道如何创建它,因为我事先不知道结构的深度。
我知道 id 1 是所有其他 id 的父级,我不需要包含它。数据框行不一定按层级排序。
[{ id: 2,
descr: Tom,
nodes: [{id: 5,
descr: Eddy},
{id: 6,
descr: Lisa}
]
},
{ id: 3,
descr: Mark,
nodes: [{id: 7,
descr: Anna,
nodes: [{id: 9,
descr: Ali
}]
},
{id: 8,
descr: Maria}
]
{ id: 4,
descr: Tony}
]
提前感谢您的帮助!
【问题讨论】:
-
所以 Parent_id = 1 是一个特例,意味着节点应该在顶级列表中?您还保证 id 是按升序排列的,其中 id 在显示为 Parent_id 之前显示为 Child_id?
标签: python dictionary data-structures nested recursive-datastructures