skip to Main Content

I have a dataframe that looks like:

From To
Flare Analytics
Analytics Cluster
Cluster AgglomerativeCluster
Cluster CommunityStructure
Analytics Graph
Graph CommunityStructure
Graph LinkDistance
Flare Data

I need it to look exactly like this format in the below link for the echart to be produced: https://github.com/andfanilo/streamlit-echarts-demo/blob/master/data/flare.json

Conversion to a normal dictionary doesn’t work. It needs to be formatted as a hierarchical dictionary with multiple levels of parent-child relationships.

    {
  "name": "flare",
  "children": [
    {
      "name": "analytics",
      "children": [
        {
          "name": "cluster",
          "children": [
            {
              "name": "AgglomerativeCluster",
              "value": 3938
            }, ...
    

This is so I can make the expandable tree graph like in: https://echarts.streamlit.app/

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    Managed it. Needed to add a level column and a value

    If I add a level column based on the tier (0,1,2)

    df.columns=["parent_id","child_id","level"]

    st.write(hs_input_output_hs_df) def recurse(parent_id, level): # create the base result result = {"name": parent_id} #, "level": int(level)

    # get all of the children of this parent, one level below this one
    children = df[(df.parent_id == parent_id) & (df["level"] == level + 1)]
    
    # if there are no such children, then return without a _children key
    if children.empty:
        result["value"]=1
        return result
    
    # otherwise, recurse on each child_id
    result["children"] = [recurse(child_id, level + 1) for child_id in sorted(children.child_id.unique())]
    
    return result
    

    tree = [recurse(parent_id, 0) for parent_id in sorted(df[df["level"] == 1].parent_id.unique())]

    st.write(tree[0])


  2. This can be done with pandas.
    import pandas with
    import pandas as pd

    And convert dataframe to dictionary with

    dictionary = dataframe.to_dict()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search