如何将Pandas DataFrame转换为树形数据结构(递归实现)
递归实现Pandas DataFrame转嵌套树形结构
你的问题在于当前代码生成的是所有包含子节点的节点的扁平集合,而非完全嵌套的树形结构。递归方法的核心是从根节点出发,为每个节点逐层递归构建其子节点的嵌套结构,最终形成符合要求的树形列表。
完整实现代码
import pandas as pd import json data = [ ['1.0', 'Main section'], ['1.1', 'One subsection'], ['1.2', 'Another subsection'], ['1.3', 'And another subsection'], ['2.0', 'The second main section'], ['2.1', 'A subsection of the second main section'], ['2.1.1', 'A sub subsection'], ['2.1.2', 'Another sub subsection'], ['2.1.2.1', 'I am a deep subsection'], ['2.1.2.2', 'I am another deep subsection'], ] df = pd.DataFrame(data, columns=['section', 'title']) # 生成parent列,标记每个节点的父节点 def add_parent(val): parts = val.split('.') # 根节点(如1.0)的父节点为None if len(parts) == 2 and parts[1] == '0': return None # 其他节点取去掉最后一部分的路径,补0形成父节点标识 parent_parts = parts[:-1] if len(parent_parts) == 1: parent_parts.append('0') parent = '.'.join(parent_parts) return parent if parent != val else None df['parent'] = df['section'].apply(add_parent) # 将数据转换为字典,方便通过section快速查找节点 node_dict = {row['section']: {'section': row['section'], 'title': row['title']} for _, row in df.iterrows()} # 递归函数:根据section获取完整的嵌套节点 def build_tree_node(section): node = node_dict[section].copy() # 找到当前节点的所有子节点 children_sections = df[df['parent'] == section]['section'].tolist() if children_sections: node['children'] = [build_tree_node(child) for child in children_sections] return node # 获取所有根节点(parent为None的节点) root_sections = df[df['parent'].isna()]['section'].tolist() # 构建完整树形结构 tree = [build_tree_node(root) for root in root_sections] # 输出验证 print(json.dumps(tree, indent=2))
输出结果
运行代码后将得到你预期的嵌套树形结构:
[ { "section": "1.0", "title": "Main section", "children": [ { "section": "1.1", "title": "One subsection" }, { "section": "1.2", "title": "Another subsection" }, { "section": "1.3", "title": "And another subsection" } ] }, { "section": "2.0", "title": "The second main section", "children": [ { "section": "2.1", "title": "A subsection of the second main section", "children": [ { "section": "2.1.1", "title": "A sub subsection" }, { "section": "2.1.2", "title": "Another sub subsection", "children": [ { "section": "2.1.2.1", "title": "I am a deep subsection" }, { "section": "2.1.2.2", "title": "I am another deep subsection" } ] } ] } ] } ]
关键步骤说明
- 节点字典构建:将DataFrame记录转为以
section为键的字典,实现O(1)时间复杂度的节点查找,提升递归效率。 - 递归节点构建:
build_tree_node函数先获取当前节点的基础信息,再查找所有子节点并递归构建子节点的嵌套结构,最终将子节点列表作为children属性添加到当前节点。 - 根节点收集:筛选出父节点为
None的顶层节点,依次调用递归函数构建完整的树形结构。
内容的提问来源于stack exchange,提问作者Simon1
相关产品推荐
相关产品推荐

