首页 > 解决方案 > 在 Python 中将叶值从数据帧动态传递到 n-ary 树

问题描述

给定如下数据框:

  root subroot leaf  value  
0    A      B1   C1     58  
1    A      B1   C2      7  
2    A      B2   C1      0 
3    A      B2   C2     20 

和代码如下:

from collections import deque

class Node:
    def __init__(self, name, weight, children):
        self.name = name
        self.children = children
        self.weight = weight
        self.weight_plus_children = weight

    def get_all_weight(self):
        if self.children is None:
          return self.weight_plus_children
        for child in self.children:
            self.weight_plus_children += child.get_all_weight()
        return self.weight_plus_children

    
def print_tree(root: Node):
    queue = deque()
    queue.append(root)
    while queue:
        front = queue.popleft()
        print('{} = {}'.format(front.name, front.weight_plus_children))
        if front.children:
            for child in front.children:
                if child is not None:
                    queue.append(child)


leaf1 = Node('C1', 58, None)
leaf2 = Node('C2', 7, None)
leaf3 = Node('C1', 0, None)
leaf4 = Node('C2', 20, None)

subroot = Node('B1', 0, [leaf1, leaf2])
subroot1 = Node('B2', 0, [leaf3, leaf4])

root = Node('A', 0, [subroot, subroot1])

root.get_all_weight()

print_tree(root)

如何df动态地将叶子值传递给下一个叶子?

我这样做的主要想法是我想读取 excel 文件并将叶子值传递给代码:

leaf1 = Node('C1', 58, None)
leaf2 = Node('C2', 7, None)
leaf3 = Node('C1', 0, None)
leaf4 = Node('C2', 20, None)

我们可以input=1使用:过滤 's 行df.loc[df['input'] == 1]

预期输出:

A = 85
B1 = 65
B2 = 20
C1 = 58
C2 = 7
C1 = 0
C2 = 20

谢谢你的帮助。

标签: python-3.xpandasalgorithmrecursiontree

解决方案


推荐阅读