Search code examples
pythonpandasdataframepandas-styles

Formatting strings in multi-index dataframes


Contex: I have a multi-index dataframe and I'd like to apply formatting to some of the columns in this table using the style and format method.

Desired output:

How can we apply the formatting so that the [(MultiIndex_1,Percentage)] and [(MultiIndex_2,Percentage)] have the format as {:.0%} ?

image

Attempts: I was trying to grab the columns that have "Percentage" as such but doesn't work:

idx = pd.IndexSlice

slice_ = idx[idx[:,:], idx[:,'Percentage']]
slice_
(df.style
.format({slice_:'{:.0%}'})
.background_gradient(
    cmap=cmap_red_green,
    subset=equity_impact.columns.get_loc_level('Percentage',level=1)[0])
)

Even if not using index, how can I format this using the actual colum names? This doesn't work either:

(df.style
.format({'[(MultiIndex_1,Percentage)]':'{:.0%}'})

Solution

  • This worked for me:

    idx = pd.IndexSlice
    (dataframe.style
      .background_gradient(
        cmap=cmap_red_green,
        subset=dataframe.columns.get_loc_level('Percentage',level=1)[0])
      .format("{:.0%}",subset=idx[:, idx[:,'Percentage']]))
    
    )