pandasdataframepandas-styles

Styling the background color of pandas index cell


I want to change the background styling color of the pandas table.

Example:

df = pd.DataFrame({
'group': ['A','B','C','D'],
'var1': [38, 1.5, 30, 4],
'var2': [29, 10, 9, 34],
'var3': [8, 39, 23, 24],
'var4': [7, 31, 33, 14],
'var5': [28, 15, 32, 14]
})

df.set_index('group', inplace=True)

I want the background color of the index cell (and just the index cell) A,C in blue and B,D in red.

I looked at the styling documentation but I could not find an example that matches this case.


Solution

  • This feature is not currently available and the next release for this might be December 2021 (https://github.com/pandas-dev/pandas/pull/41893). However, you can easily work around this by using table styles. See my answer below:

    df = pd.DataFrame([[1,2],[3,4],[5,6],[7,8]], index=["A", "B", "C", "D"])
    green = [{'selector': 'th', 'props': 'background-color: green'}]
    red = [{'selector': 'th', 'props': 'background-color: red'}]
    df.style.set_table_styles({"A": green, "B": red, "C": green, "D": red}, axis=1)
    

    enter image description here