plotly - remove or ignore "Non-leaves rows" for sunburst diagram

Viewed 165

I have a DataFrame with some "Non-leaves rows" in it. Is there any way to get plotly to ignore them, or a way to automatically remove them?

Here's a sample DataFrame:

0 1 2 3
0 Alice Bob
1 Alice Bob Carol David
2 Alice Bob Chuck Delia
3 Alice Bob Chuck Ella
4 Alice Bob Frank

In this case, I get the error Non-leaves rows are not permitted in the dataframe because the 0th row is not a distinct leaf.

I've tried using df = df.replace(np.NaN, pd.NA).where(df.notnull(), None) to add the None to the empty values, but the error persists.

Is there any way to have the non-leaves ignored? If not, is there a simple way to prune them? My real dataset is several thousand rows.

1 Answers

One way is to reshape your dataframe with unique relations parent-child. Here is one way:

import plotly.express as px

cols = df.columns
data = (
    pd.concat(
        [df[[i,j]].rename(columns={i:'parents',j:'childs'})
         for i,j in zip(cols[:-1], cols[1:])])
      .drop_duplicates()
)

fig = px.sunburst(data, names='childs', parents='parents')
fig.show()
Related