问题
Given a dataframe as follows:
root subroot leaf value
0 A B1 C1 58
1 A B1 C2 7
2 A B2 C1 0
3 A B2 C2 20
and code as follows:
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)
How could I pass leaf values from df
to the following leaf dynamically?
The main ideas I'm doing this is I want to read excel files and pass leaf values to the code:
leaf1 = Node('C1', 58, None)
leaf2 = Node('C2', 7, None)
leaf3 = Node('C1', 0, None)
leaf4 = Node('C2', 20, None)
We can filter input=1
's rows with: df.loc[df['input'] == 1]
.
Output expected:
A = 85
B1 = 65
B2 = 20
C1 = 58
C2 = 7
C1 = 0
C2 = 20
Thanks for your kind help.
来源:https://stackoverflow.com/questions/62908135/dynamically-pass-leaf-values-from-dataframe-to-n-ary-tree-in-python