python-3.x - 在 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
谢谢你的帮助。
解决方案
推荐阅读
- azure-devops - Azure DevOps 给出“无法访问页面”错误
- discord.py - 如何检测两个变量是否具有相同的值
- javascript - 在 Promise 解析中为外部 API 设置超时
- excel - 结合多个正则表达式模式VBA
- javascript - FlatList RefreshControl 在 Android 上不起作用
- html - 如何在 HTML 中使用脚本的相对路径
- docker-compose - Docker撰写不写入本地文件夹
- python - 在 Python 中的字典列表中提取最优解
- javascript - Javacript 计算在 EDIT MODAL 中不起作用,从数据库加载值
- reactjs - 如何正确对齐 React Material ui Grid 中的图像?