Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
Federico Vega Avatar asked Nov 26 '25 12:11

Federico Vega


2 Answers

Based on the limitations of df.style, coloring index and columns is not implemented.

If you are okay to color the values based on the index, you can do something like this. Create a dictionary and apply the color based on the index using index.map

c1 = 'background-color: blue'
c2 = 'background-color: red'
d = {"A":c1,"B":c2,"C":c1,"D":c2}

df.style.apply(lambda x: x.index.map(d))

enter image description here

like image 61
anky Avatar answered Nov 29 '25 02:11

anky


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

like image 33
Attack68 Avatar answered Nov 29 '25 00:11

Attack68



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!