Skip to content
Advertisement

How to highlight the column in Pandas Dataframe with MultiIndex / advanced indexing by the condition

Could you, please, help me with highlighting the columns in my dataframe with multiindex/advanced indexing?

I have the code which forms the Table 1:

pivot_clicks = pd.pivot_table(data=clicks, index='Источник', columns='Дата', 
                       values=['Разница в процентах']).sort_index(axis=0, ascending=False)
pivot_clicks = pivot_clicks.swaplevel(0,1, axis=1).sort_index(axis=1, ascending=False)#.reset_index()
pivot_clicks = pivot_clicks.sort_values([pivot_clicks.columns[0]], ascending=False)

So, (2022-02-27, ‘Разница в процентах’), (2022-02-26, ‘Разница в процентах’), etc. are columns in this table in python and ‘Источник’ is an index.

enter image description here

I want to highlight the columns, where the values >= 15, and make it red. Please, help me with that, because I can’t deal with multiindex well.

Advertisement

Answer

Multi-indexed columns can be accessed with tuples. e.g. pivot_clicks.loc[:, [("2022-02-27", 'Разница в процентах'), ("2022-02-26", 'Разница в процентах')]]

And working example for styling a single column:

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
                         "bar", "bar", "bar", "bar"],
                   "B": ["one", "one", "one", "two", "two",
                         "one", "one", "two", "two"],
                   "C": ["small", "large", "large", "small",
                         "small", "large", "small", "small",
                         "large"],
                   "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
                   "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
pivot = pd.pivot_table(df, values='D', index=['C'],
                    columns=['A', "B"], aggfunc=np.sum)
pivot.style.applymap(lambda x: f"color: {'red' if x > 4.5 else 'black'}", subset=[("bar", "one")])
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement