Search code examples
pythonpandasgspread

comparing two columns and highlighting differences in dataframe


What would be the best way to compare two columns and highlight if there is a difference between two columns in dataframe?

df = pd.DataFrame({'ID':['one2', 'one3', 'one3', 'one4' ],
                   'Volume':[5.0, 6.0, 7.0, 2.2],
                   'BOX':['one','two','three','four'],
                   'BOX2':['one','two','five','one hundred']})

I am trying to compare the BOX column and BOX2 column and I'd like to highlight the differences between them.


Solution

  • Maybe you can do something like this:

    df.style.apply(lambda x: (x != df['BOX']).map({True: 'background-color: red; color: white', False: ''}), subset=['BOX2'])
    

    Output (in Jupyter):

    enter image description here