Home > Enterprise >  How to change the color of a dataframe header with python pandas
How to change the color of a dataframe header with python pandas

Time:05-26

I'm using this function to change the color of a specific cells:

def cell_colours(series):
 red = 'background-color: red;'
 yellow = 'background-color: yellow;'
 green = 'background-color: green;'
 default = ''

 return [red if data == "failed" else yellow if data == "error" else green if data == "passed" 
 else default for data in series]

This only changes color of each individual cell. What I need is to change the color a the header. Is there some simple way to do this? Because when I try to use

headers = {
    'selector': 'th:not(.index_name)',
    'props': 'background-color: #000066; color: white;'
}
df = df.set_table_styles([headers])
df = df.style.apply(cell_colours)

It's giving me an error that it's not a table. I guess I need to find some method that can change only the header of the dataframe.

Thanks!

CodePudding user response:

You can use .col_heading selector

headers = {
    'selector': 'th.col_heading',
    'props': 'background-color: #000066; color: white;'
}
s = df.style.set_table_styles([headers])\
            .apply(cell_colours)
s.to_html('output.html')

enter image description here

CodePudding user response:

Maybe you can try ax.table to color headers

import pandas as pd
import matplotlib.pyplot as plt

fig = plt.figure()    
ax = fig.add_subplot

tab = ax.table(cellText=df.values, colLabels=df.columns,cellLoc='left', rowLoc='left', loc='bottom', 
         colLoc = 'left', colColours =["palegreen"] * 10, bbox=[0.0,-0.45,1,.28])
  • Related