Home > OS >  Highlight a row in a pandas df if that row also appears in another df
Highlight a row in a pandas df if that row also appears in another df

Time:01-10

I have two dataframes df1 and df2. I would like to highlight in yellow all the rows in df1 that are also present in df2.

enter image description here


Alternatively, to actually do the comparison inside the function, define a set of tuples of df2 rows beforehand:

set_df2 = set(df2.apply(tuple, axis=1))

def highlight_rows(row):
    color = 'yellow' if tuple(row) in set_df2 else ""
    return [f'background-color: {color}'] * len(row)

df1.style.apply(highlight_rows, axis=1)
  • Related