简体   繁体   中英

Highlighting multiple cells in a row based on other values in the row in a Pandas DataFrame

I am trying to highlight cells in my pandas dataframe based on two conditions:

  • If A cell - B cell > 10 highlight B cell in green else if ((B cell - A cell)/B cell * 100) > 20 highlight B cell in red

  • If A cell - C cell > 10 highlight C cell in green else if ((C cell - A cell)/C cell * 100) > 20 highlight C cellin red

i  A  B  C   D
0  4  2  3  Jim
1  3  3  2  Bob
2  3  2  4  Joe

I tried some variations of apply() and applymap() with subset but I wasn't able to do what i wanted.

Try looking at : https://xlsxwriter.readthedocs.io/

You'll basically end up with something like:

    excel_file = StringIO.StringIO()
    writer = pd.ExcelWriter(excel_file,
                            engine='xlsxwriter')
    some_data_frame.to_excel(writer,
                             sheet_name='some_sheet_name',
                             engine='xlsxwriter',
                             encoding='utf-8')
    worksheet = writer.sheets['some_sheet_name']
    worksheet.conditional_format('B',
                                 {'type': 'cell',
                                  'criteria': '>=',
                                  'value': 5,
                                  'format': hot
                                  })
    writer.save()
    writer.close()

In your case you would set the value equal to your calculation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM