Issue
I generate a report from the pandas Data Frame. I need to divide headings into 3 sections. This is what my DF looks like:
| A | B | C | D | E | F |
|11 |10 |9,7|-2,3|802|64,4|
|24 |10 |9,1|0,2 |725|66,1|
|19 |20 |9,9|3,91|798|58,3|
Right now my headings have the same background colour but I need to divide them into 3 different sections. Headers A and B should have the same background colour lest say for example blue, headers C and D should have the colour green, and headers E and F should have the colour yellow. How to do that? Thanks for any help.
Solution
You can use set_table_styles
and a dictionary to map the column names to their color:
colors = {'A': 'blue', 'B': 'blue',
'C': 'green', 'D': 'green',
'E': 'yellow', 'F': 'yellow'
}
df.style.set_table_styles(
[{
'selector': f'th.col{i}',
'props': [('background-color', color)]
} for i, color in enumerate(df.columns.map(colors))
])
If you have a MultiIndex and further need to select the level, use f'th.level0.col{i}'
variant by position
colors = ['blue', 'green', 'yellow']
N = len(colors) # 3
df.style.set_table_styles(
[{
'selector': f'th.level0.col{i}',
'props': [('background-color', colors[i//(df.shape[1]//N)])]
} for i in range(df.shape[1])
])
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.