Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight a specific cell in a pandas dataframe

Tags:

python

pandas

I'd like to highlight a specific cell in my pandas dataframe. I can grab the exact position using the .loc[] function. I've tried to look at some examples using df.style.apply(lambda x: ['background color: yellow' ...] but I am not sure how to pass in the exact position I am trying to access to format.

My dataframe has a multi index so to access a specific cell I use: df.loc[(i1,i2,i3,i4,i5),col1] and this would indicate the cell I want formatted.

Thanks in advance.

like image 204
cap Avatar asked Oct 28 '25 05:10

cap


1 Answers

For a specific cell, you can do:

# toy example
df = pd.DataFrame({'i1':[0,0,0,1,1,1],
                   'i2':[0,1,2,0,1,2],
                   'col1':[1,2,3,4,5,6]}).set_index(['i1','i2'])

subsets = pd.IndexSlice[(0,1), 'col1']
df.style.applymap(lambda x: "background-color: yellow", subset=subsets)

Which will hightlight the cell [(0,1), 'col1'].

like image 193
Quang Hoang Avatar answered Oct 29 '25 18:10

Quang Hoang



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!