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')
pandas文档的section解释了如何使用条件格式将数据帧导出到excel。你知道吗
下面是一个简单的例子:
不能导出条件格式,但可以使用模块
xlsxwriter
https://xlsxwriter.readthedocs.io/example_conditional_format.html#ex-cond-format
相关问题 更多 >
编程相关推荐