kayjan / bigtree

Tree Implementation and Methods for Python, integrated with list, dictionary, pandas and polars DataFrame.

Home Page:https://bigtree.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Migration from anytree to bigtree

clabnet opened this issue · comments

I would migrate from anytree to bigtree.

With this data

item | parent 
H-FUQF | NaN 
FUQF.ALB.22.100 | H-FUQF 
2999-12353-01- | FUQF.ALB.22.100 
221355-090-2 | 2999-12353-01- 
2922-01366-01- | 2999-12353-01-

this "anytree" code work fine

from anytree import Node, RenderTree

# create the tree
root = None
nodes = {}
no_parent = {}

for id, parent in zip(df_slim["item"], df_slim["parent"]):
    if type(parent) == float and  np.isnan(parent) :

        node = Node(id)
        root = node
        nodes[id] = node
    else:
        if not parent in nodes:
            node = Node(id)
            no_parent[id] = [node, parent]
        else:
            node = Node(id, nodes[parent])
            nodes[id] = node

for i, np in no_parent.items():
    np[0].parent = nodes[np[1]]
print(RenderTree(root))
Node('/H-FUQF')
└── Node('/H-FUQF/FUQF.ALB.22.100')
    └── Node('/H-FUQF/FUQF.ALB.22.100/2999-12353-01-')
        ├── Node('/H-FUQF/FUQF.ALB.22.100/2999-12353-01-/221355-090-2')
        ├── Node('/H-FUQF/FUQF.ALB.22.100/2999-12353-01-/2922-01366-01-')
        ├── Node('/H-FUQF/FUQF.ALB.22.100/2999-12353-01-/242241-402-1')

Please, how to convert above code to run using bigtree ?
Thank's in advance

If I can break down what you're trying to do - you're trying to convert the dataframe (with parent-child relation) to tree, and then do a print of the tree to console.

This can be done with two lines of code! Below is a working example of how it can be done,

# Setup: Create your DataFrame first

import pandas as pd

df_slim = pd.DataFrame(
    [
        ["H-FUQF", None],
        ["FUQF.ALB.22.100", "H-FUQF"],
        ["2999-12353-01-", "FUQF.ALB.22.100"],
        ["221355-090-2", "2999-12353-01-"],
        ["2922-01366-01-", "2999-12353-01-"],
    ],
    columns=["item", "parent"]
)

Using bigtree,

from bigtree import dataframe_to_tree_by_relation

# Convert dataframe to tree
root = dataframe_to_tree_by_relation(df_slim, child_col="item", parent_col="parent")

# Print tree to console
root.show()

This will result in the output

H-FUQF
└── FUQF.ALB.22.100
    └── 2999-12353-01-
        ├── 221355-090-2
        └── 2922-01366-01-

Do let me know if it works! 😄

Yes it work, thank's!