Python – color DF cell by hex value in cell

Question:

I have a data frame that contains hex values in two columns. I would like to visualize the hex value with color swatches either by coloring the cell itself or adding a column with a color swatch. Example table is below.

hex1 hex 2
#dcddde #ffba00
#954eff #b889ff

Desired output is as follows

enter image description here

or

enter image description here

Asked By: MappyCoding

||

Answers:

DataFrame.style is what you’re after:

import pandas as pd
df = pd.DataFrame({"hex1":["#dcddde", "#954eff"], "hex2":["#ffba00","#b889ff"]})

df.style.applymap(lambda hex_color: f"background-color: {hex_color}")
Answered By: Seon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.