【问题标题】:Grouped Dataframe to a nested tree in python将数据框分组到python中的嵌套树
【发布时间】:2022-11-08 09:16:56
【问题描述】:

我有一个数据框

grpdata = {'Group1':['A', 'A', 'A', 'B','B'],
        'Group2':['A2','B2','B2','A2','B2'],
        'Group3':['A3', 'A3', 'B3','A3', 'A3'],
        'Count':['10', '12', '14', '20']}
 
# Convert the dictionary into DataFrame 
groupdf = pd.DataFrame(grpdata)

我想将此数据帧转换为一棵树,其中每一行都是从根节点到叶节点的路径。

我尝试使用中显示的方法 Read data from a pandas dataframe and create a dataframe using anytree in python

def add_nodes(nodes, parent, child):
    if parent not in nodes:
        nodes[parent] = Node(parent)  
    if child not in nodes:
        nodes[child] = Node(child)
    nodes[child].parent = nodes[parent]

nodes = {}  
for parent, child in zip(groupdf["Group1"],groupdf["Group2"]):

    add_nodes(nodes, parent, child)

但是,我无法弄清楚如何在上面定义的相同节点结构中将 Group3 作为子节点添加到 Group2 作为父节点。

roots = list(groupdf[~groupdf["Group1"].isin(groupdf["Group2"])]["Group1"].unique())



for root in roots:         
    for pre, _, node in RenderTree(nodes[root]):
    print("%s%s" % (pre, node.name))

如何将后续列“Group3”和“Count 添加到此树结构中?

【问题讨论】:

    标签: python dataframe tree


    【解决方案1】:

    bigtree 是一个 Python 树实现,集成了 Python 列表、字典和 pandas DataFrame。

    对于这种情况,有一个内置的 dataframe_to_tree 方法可以为您执行此操作。

    import pandas as pd
    from bigtree import dataframe_to_tree, print_tree
    
    # I changed the dataframe to path column and count column
    # I also added a `root` over here since trees must start from same root
    path_data = pd.DataFrame([
        ["root/A/A2/A3", 10],
        ["root/A/B2/A3", 12],
        ["root/A/B2/B3", 14],
        ["root/B/A2/A3", 20],
        ["root/B/B2/A3", 25],
    ],
        columns=["Path", "Count"]
    )
    root = dataframe_to_tree(path_data)
    print_tree(root, attr_list=["Count"], style="const")
    

    这导致输出,

    root [Count=None]
    ├── A [Count=None]
    │   ├── A2 [Count=None]
    │   │   └── A3 [Count=10]
    │   └── B2 [Count=None]
    │       ├── A3 [Count=12]
    │       └── B3 [Count=14]
    └── B [Count=None]
        ├── A2 [Count=None]
        │   └── A3 [Count=20]
        └── B2 [Count=None]
            └── A3 [Count=25]
    

    资料来源:bigtree 的创建者;)

    【讨论】:

      猜你喜欢
      • 2023-02-09
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 2021-11-05
      • 2022-12-05
      • 2017-06-14
      • 2020-03-13
      • 1970-01-01
      相关资源
      最近更新 更多