[英]How to export the Pandas conditional formatting to an Excel file
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.但是,现在我想在不丢失颜色格式的情况下将数据框导出到 Excel 文件。 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)
you can't export pandas conditional formatting but you can use the module xlsxwriter
您不能导出xlsxwriter
条件格式,但可以使用模块xlsxwriter
https://xlsxwriter.readthedocs.io/example_conditional_format.html#ex-cond-format https://xlsxwriter.readthedocs.io/example_conditional_format.html#ex-cond-format
This section of the pandas documentation explains how dataframes can be exported to excel with conditional formatting. pandas 文档的这一部分解释了如何使用条件格式将数据框导出到 excel。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.