Is there a way to read data from a pandas DataFrame and construct a tree using anytree?
Parent Child
A A1
A A2
A2 A21
I can do it with static values as follows. However, I want to automate this by reading the data from a pandas DataFrame with anytree.
>>> from anytree import Node, RenderTree
>>> A = Node("A")
>>> A1 = Node("A1", parent=A)
>>> A2 = Node("A2", parent=A)
>>> A21 = Node("A21", parent=A2)
Output is
A
├── A1
└── A2
└── A21
This question AND especially the ANSWER has been adopted, copied really, from:
Read data from a file and create a tree using anytree in python
Many thanks to @Fabien N
Create nodes first if not exist, store their references in a dictionary
nodes
for further usage. Change parent when necessary for children. We can derive roots of the forest of trees by seeing whatParent
values are not inChild
values, since a parent is not a children of any node it won't appear inChild
column.Result:
Update printing a specific root: