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/
2
Answers
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)
tree = [recurse(parent_id, 0) for parent_id in sorted(df[df["level"] == 1].parent_id.unique())]
st.write(tree[0])
This can be done with pandas.
import pandas with
import pandas as pd
And convert dataframe to dictionary with
dictionary = dataframe.to_dict()