Home > Back-end >  Highlight element based on boolean pandas df
Highlight element based on boolean pandas df

Time:05-14

I have 2 data frames with identical indices/columns:

df = pd.DataFrame({'A':[5.5, 3, 0, 3, 1],
                     'B':[2, 1, 0.2, 4, 5],
                     'C':[3, 1, 3.5, 6, 0]})

df_bool = pd.DataFrame({'A':[0, 1, 0, 0, 1],
                          'B':[0, 0, 1, 0, 0],
                          'C':[1, 1, 1, 0, 0]})

I want to apply a style function to df element-wise using df_bool as a mask.

This is the expected result:

expected results

Current failed function

def color_boolean(val):
  color =''
  if df_bool == 1:
    color = 'red'
  elif df_bool == 0:
    color = 'black'
  return f'color: {color}'

df.head().style.apply(color_boolean, axis=None)
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

CodePudding user response:

You can use a function that ignores the input and simply uses the other DataFrame:

def color_boolean(val):
    return f'color: {"red" if val else "black"}'

df.style.apply(lambda _: df_bool.applymap(color_boolean), axis=None)

or:

df.style.apply(lambda c: df_bool[c.name].apply(color_boolean))

output:

dataframe style

CodePudding user response:

You can also use Styled DataFrame with red colored text where df == 1 is True


Optional Styled DataFrame with red text including formatted rounding


Imports (and versions):

import numpy as np  # 1.22.3
import pandas as pd  # 1.4.2
  • Related