You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于pandas父子关系表生成层级化父子节点关联结果

解法

核心实现逻辑为通过广度优先遍历(BFS)遍历完整的层级树,每遍历到一个父节点就输出它和所有直接子节点的配对,只要子节点自身还有下级子节点,就将该子节点作为下一级父节点加入遍历队列即可。

完整代码实现

import pandas as pd
from collections import deque

# 示例输入:你当前拿到的原始父子表
raw_df = pd.DataFrame({
    "parent_id": [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 2010, 2010, 2010, 3000, 3000, 3011],
    "child_id": [2010, 2100, 2110, 3000, 3011, 3033, 3102, 3111, 3011, 3102, 4001, 3011, 3033, 3050]
})

# 1、构建父节点到子节点列表的映射
children_map = raw_df.groupby("parent_id")["child_id"].apply(list).to_dict()

# 2、自动识别根节点(所有没有作为子节点出现的ID,不需要硬编码根节点)
all_child_ids = set(raw_df["child_id"])
root_nodes = [pid for pid in raw_df["parent_id"].unique() if pid not in all_child_ids]

# 3、广度优先遍历生成层级结果
result = []
queue = deque(root_nodes)
while queue:
    current_parent = queue.popleft()
    if current_parent not in children_map:
        continue
    for child in children_map[current_parent]:
        result.append({"parent_id": current_parent, "child_id": child})
        # 只要子节点有下级节点,就加入队列作为下一级父节点
        if child in children_map:
            queue.append(child)

# 4、输出最终结果
result_df = pd.DataFrame(result)
print(result_df)

补充说明

  • 如果你的原始数据中已经包含了所有层级的直接父子关系,只需要将所有直接父子对都录入原始表,代码会自动输出完整的层级结果
  • 代码默认适配多根节点的场景,不需要手动指定根节点ID

内容的提问来源于stack exchange,提问作者Reison

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 03:33:02