Created
September 5, 2019 13:07
-
-
Save chamoda/308adff923492d063fda76937d981d0e to your computer and use it in GitHub Desktop.
Convert a tree to tabular structure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from anytree import AnyNode, RenderTree, PreOrderIter | |
from pandas import DataFrame | |
root = AnyNode(id=1, name="Parent", children=[ | |
AnyNode(id=2, name="Child1", children=[ | |
AnyNode(id=4, name="GrandChild1"), | |
AnyNode(id=5, name="GrandChild2"), | |
]), | |
AnyNode(id=3, name="Child2", children=[ | |
AnyNode(id=6, name="GrandChild1"), | |
AnyNode(id=7, name="GrandChild2"), | |
]) | |
]) | |
print(RenderTree(root)) | |
rows = [] | |
for node in PreOrderIter(root): | |
rows.append((node.id, node.name, int(node.parent.id) if not node.is_root else 0)) | |
dataFrame = DataFrame(rows, columns=("Id", "Name", "Parent")) | |
print(dataFrame) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment