0

So i am trying to create hyerarchy tree which using pandas from an mysql table.This is my code below:

import mysql.connector as sql
import pandas as pd
import json


db_connection = sql.connect(host='localhost', database='tutorialdb', user='root', password='12345')

db_cursor = db_connection.cursor()

query = db_cursor.execute('SELECT * FROM users3')

table_rows = db_cursor.fetchall()

df = pd.DataFrame(table_rows)
df= df.columns['id', 'name', 'parent_id', 'child_id','surname']





def build_tree(df, parent_id=None):
    if parent_id is not None:
        parent_id = int(parent_id)
    children = df[df["parent_id"] == parent_id]
    if len(children) == 0:
        return {}
    else:
        tree = {}
        for id, child in children.iterrows():
            node = {"name": child["name"], "surname": child["surname"]}
            node.update(build_tree(df, child["child_id"]))
            tree[child["child_id"]] = node
        return tree


tree = build_tree(df, parent_id=None)

tree_json = json.dumps(tree, indent=4)

Im getting this error: IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices.

Im trying to resolve this issue with sqlqueries only but then im getting error as too many connections.What should i do?


My DF example: DF

So heres the thing i want to create a user tree.If arthur logged the website the output should be like this: arthur's view

newbieeee
  • 1
  • 1

0 Answers0