Given the following Pandas DataFrame (the original DataFrame has 200+ rows):
import pandas as pd
df = pd.DataFrame({
'child': ['Europe', 'France', 'Paris','North America', 'US', 'Canada'],
'parent': ["", 'Europe', 'France',"", 'North America', 'North America'],
'value': [746.4, 67.75, 2.16, 579,331.9, 38.25]
})
df
|---+---------------+---------------+--------|
| | child | parent | value |
|---+---------------+---------------+--------|
| 0 | Europe | | 746.40 |
| 1 | France | Europe | 67.75 |
| 2 | Paris | France | 2.16 |
| 3 | North America | | 579.00 |
| 4 | US | North America | 331.90 |
| 5 | Canada | North America | 38.25 |
|---+---------------+---------------+--------|
I want to generate the following JSON tree:
[
{
name: 'Europe',
value: 746.4,
children: [
{
name: 'France',
value: 67.75,
children: [
{
name: 'Paris',
value: 2.16
}
]
}
]
},
{
name: 'North America',
value: 579,
children: [
{
name: 'US',
value: 331.9,
},
{
name: 'Canada',
value: 38.25
}
]
}
];
This tree will be used as an input for ECharts visualizations, like for example this basic sunburst chart.
3
Answers
You can use the
networkx
package for this. First convert the dataframe to a graph:This will result in a weighted graph:
Next, we get the graph as a JSON formatted tree:
This will look as follows:
Finally, post-process the JSON data by adding back the values and renaming ‘id’ to ‘name’. Maybe there is a better way of doing this but the below works.
Final result:
You could first create the individual nodes as
{ name, value }
dicts, and key them by name. Then link them up:For the example,
result
would be:There is a library called
bigtree
which can do exactly what you are looking for.Also see: Read data from a pandas DataFrame and create a tree using anytree in python