Hierarchical columns on Tabulator

Hi, is it possible to use the Tabulator with a multi-columns dataframe as input ? I know that it is possible using the parameters “groups” afterwards, but then with hierarchical columns as input we have to use the tuple names (and I dont know how to modify the columns name after initialization)
Also, the pane below does not display the values, bug ?

thanks a lot

import pandas as pd
import panel as pn
pn.extension('tabulator')

df = pd.DataFrame(data=[[38.0, 2.0, 18.0, 22.0], [19, 439, 6, 452]],
                  index=pd.Index(['Tumour (Positive)', 'Non-Tumour (Negative)']),
                  columns=pd.MultiIndex.from_product([['Decision Tree', 'Regression'], ['Tumour', 'Non-Tumour']]))

display(df)
display(pn.widgets.Tabulator(df))

Possible to groups the columns with the following:

import pandas as pd
import panel as pn
pn.extension('tabulator')

df = pd.DataFrame(data=[[38.0, 2.0, 18.0, 22.0], [19, 439, 6, 452]],
                  index=pd.Index(['Tumour (Positive)', 'Non-Tumour (Negative)']),
                  columns=pd.MultiIndex.from_product([['Decision Tree', 'Regression'], ['Tumour', 'Non-Tumour']]))

groups = {group: [f"('{group}', 'Tumour')", f"('{group}', 'Non-Tumour')"] for group in df.columns.get_level_values(0).unique()}
titles1 = {(f'{group}', 'Tumour'): "Tumour" for group in df.columns.get_level_values(0).unique()}
titles2 = {(f'{group}', 'Non-Tumour'): "Non-Tumour" for group in df.columns.get_level_values(0).unique()}
titles={**titles1, **titles2}

pn.widgets.Tabulator(df.set_axis(df.columns.to_flat_index(), axis=1), groups=groups, titles=titles)

Not very clean but works when flattening the column levels beforehand

3 Likes

Thanks for coming back to share your solution. It helps both users and developers. Helps build the knowledge base.