1

I am reading excel into DataFrame, comparing the columns and color code the column for the value that does not match and writing to excel. Below is my code and it's not working. Anyone help me on this?

file = Path(path to excel)
df = pd.read_excel(file)

def highlight(row):
     if row['AMOUNT A'] != row['AMOUNT B'] and row['AMOUNT C'] != row['AMOUNT D']:
          color = 'red'
     background = ['background-color: {}'.format(color) for _ in row]
     return background
df.style.apply(highlight, subset=['IND_DB_C_INN'])

writer = pd.ExcelWriter(path to excel)
df.to_excel(writer, 'data')
writer.save()

df

AMOUNT A    AMOUNT B    AMOUNT C    AMOUNT D
1400            1400        
3000            3000        
1500            2500       2400       2300
3500            3500        

Output I want to see in excel:

enter image description here

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Bobby
  • 109
  • 8
  • As covered in [my answer](https://stackoverflow.com/a/70383791/15497888) here. The Styler that is returned from `df.style` is a _separate object_ from the `df` which creates it. `df.to_excel` is always going to produce an unstyled DataFrame since you are exporting a pandas `DataFrame`. You need to export from the `Styler` instead: `df.style.apply(highlight, axis=1).to_excel(...)` – Henry Ecker Mar 03 '22 at 01:57

0 Answers0