我有一个csv文件,其中包含id,name和parentid等数据,我想使用该数据文件绘制一棵树。请帮助
我执行了此代码,但是熊猫无法正常工作
from ete3 import Tree
import numpy as np
import csv
import pandas as pd
f=open("UdemyT21.csv","r")
csvreader=csv.reader(f)
next(f)
test=list(csvreader)
header=['ID','Name','ParentId']
mydict = {rows[0]:rows[2] for rows in test}
for key in mydict.items():
for value in mydict.items():
if value==None:
t=Tree(key)
t.show()
else:
t=Tree("(value,key);")
t.show()
答案 0 :(得分:-1)
您可以使用ete3库pip install ete3 PyQt5
。可以here找到将树导出为png的教程。
一个示例,假设您已将csv加载为数组[parent,id](假设id是名称):
from ete3 import Tree, TreeStyle, TextFace, add_face_to_node
from collections import defaultdict
def build_tree(nodes):
root = None
for i in nodes:
if i[0] == -1:
root = i
if not root:
raise ValueError('no root!')
data = defaultdict(list)
for i in nodes:
if i[0] != -1:
data[i[1]] = []
data[i[0]].append(i[1])
return data, root[1]
def dict_tree_to_str(tree, root):
if not tree[root]:
return f'{root}'
subtrees = [dict_tree_to_str(tree, st) for st in tree[root]]
return f'({",".join(subtrees)}){root}'
tree_csv = [[-1, 1], [1, 2], [1, 3], [2, 4], [3, 5], [3, 6], [5, 7]]
tree_dict, root = build_tree(tree_csv)
t = Tree(dict_tree_to_str(tree_dict, root)+';', format=1)
ts = TreeStyle()
ts.show_leaf_name = False
def my_layout(node): # https://github.com/etetoolkit/ete/issues/219
F = TextFace(node.name, tight_text=True)
add_face_to_node(F, node, column=0, position="branch-right")
ts.layout_fn = my_layout
t.render("mytree.png", w=183, units="mm", tree_style=ts)