0

I want to apply two styles to a dataframe with pandas and then export it as an excel file.

Style 1 (this one is accomplished): color the entire row with according column color

Style 2 (get stuck): if condition 2, color just one cell for a particular column

I want my excel file to look as follow. The row color is based on values of a certain column (which stores the color code). And the cell color (purple) for 'Timestamp' column is based on whether the time difference from now exceeds 24 hrs. enter image description here

I managed to get style 1 applied, but don't know how two roadblocks applying style 2:

  1. df.style.apply can be used two times
  2. don't know how to code up highlight_timeout function
# color dataframe based on column 'AlarmColor' with styler
def highlight_rows(row):
    value = row.loc['AlarmColor']
    return ['background-color: {}'.format(value) for r in row]

def highlight_timeout(dt):
    [## something here ##]
    return [## something ##]

# apply pre-defined styles
df = df.style.apply(highlight_rows, axis=1)
styles = df.style.apply(highlight_timeout, subset=['TimeStamp'])   # <- this throws error

# write to excel
writer = pd.ExcelWriter(f"{project_name}_{current_time}.xlsx", engine='xlsxwriter')
styles.to_excel(writer, sheet_name='Your sheet name', columns=cols, index=False)  # send df to writer
writer.save()

Thanks

Looked up this article How to color a value in a dataframe based on a condition and export it to a csv file?

Kevin
  • 39
  • 6

0 Answers0