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:
JavaScript
x
5
1
pivot_clicks = pd.pivot_table(data=clicks, index='Источник', columns='Дата',
2
values=['Разница в процентах']).sort_index(axis=0, ascending=False)
3
pivot_clicks = pivot_clicks.swaplevel(0,1, axis=1).sort_index(axis=1, ascending=False)#.reset_index()
4
pivot_clicks = pivot_clicks.sort_values([pivot_clicks.columns[0]], ascending=False)
5
So, (2022-02-27, ‘Разница в процентах’), (2022-02-26, ‘Разница в процентах’), etc. are columns in this table in python and ‘Источник’ is an index.
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:
JavaScript
1
16
16
1
import pandas as pd
2
import numpy as np
3
4
df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
5
"bar", "bar", "bar", "bar"],
6
"B": ["one", "one", "one", "two", "two",
7
"one", "one", "two", "two"],
8
"C": ["small", "large", "large", "small",
9
"small", "large", "small", "small",
10
"large"],
11
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
12
"E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
13
pivot = pd.pivot_table(df, values='D', index=['C'],
14
columns=['A', "B"], aggfunc=np.sum)
15
pivot.style.applymap(lambda x: f"color: {'red' if x > 4.5 else 'black'}", subset=[("bar", "one")])
16