Reputation: 23
I have applied the following conditional formatting to a dataframe. Now, however, I want to export the dataframe to an Excel file without losing the colour formatting. Any ideas?
def highlight(ex):
if ex.Monatsgehalt_September == 0 or ex.Bonus == 0:
return ['color: red']*col
else:
return ['color: black']*col
ex.style.apply(highlight, axis=1)
Upvotes: 1
Views: 3017
Reputation: 8633
This section of the pandas documentation explains how dataframes can be exported to excel with conditional formatting.
Here's a simple example:
import pandas as pd
import numpy as np
# Initialize example dataframe
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1)
df.iloc[0, 2] = np.nan
def highlight_max(s):
"""Styling function: highlights the maximum in a Series yellow."""
is_max = s == s.max()
return ['background-color: yellow' if v else '' for v in is_max]
def color_negative_red(val):
"""Styling function: apply red font color to negative values."""
color = 'red' if val < 0 else 'black'
return f'color: {color}'
# Apply conditional formatting to dataframe
styled = df.style.applymap(color_negative_red).apply(highlight_max)
# Export styled dataframe to excel
styled.to_excel('styled.xlsx', engine='xlsxwriter')
Upvotes: 2
Reputation: 620
you can't export pandas conditional formatting but you can use the module xlsxwriter
https://xlsxwriter.readthedocs.io/example_conditional_format.html#ex-cond-format
Upvotes: 1