Home > Software engineering >  Python - color DF cell by hex value in cell
Python - color DF cell by hex value in cell

Time:09-09

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

CodePudding user response:

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}")
  • Related