考虑下面的这个假人DataFrame
:
df = pd.DataFrame(np.random.rand(15).reshape(5,3), columns='x y z'.split())
# df
x y z
0 0.725005 0.318429 0.918186
1 0.883890 0.993736 0.795322
2 0.687472 0.328307 0.108520
3 0.608381 0.193478 0.469421
4 0.598708 0.276778 0.433235
假设应用了以下简单的 pandas 样式:
style = df.style \
.set_table_styles([{'selector': 'th', 'props': [('background-color', 'orange')]}]) \
.applymap(lambda x: 'color: red' if x >.5 else 'color: blue')
style.render()
似乎证实了样式已申请th
和(下面的td
片段):
<style type="text/css" >
#T_8b7f1124_a115_11ea_8cf8_48452026764f th {
background-color: orange;
} #T_8b7f1124_a115_11ea_8cf8_48452026764frow0_col0 {
color: red;
} #T_8b7f1124_a115_11ea_8cf8_48452026764frow0_col1 {
color: blue;
} ...
将其导出为 html 会按预期显示所有颜色。但是,当我申请时to_excel
,只会拾取元素样式。标题/索引保持默认颜色:
style.to_excel(r'somefile.xlsx')
我尝试了两者xlsxwriter
并openpyxl
作为引擎,两者都表现出相同的行为。
set_table_styles
我在and上搜索了几个问题Styler.to_excel
,但似乎都关心单个元素,似乎没有解决它们的组合。也尝试在github上搜索问题日志,到目前为止还没有遇到匹配。
有人有幸set_table_styles
一起Styler.to_excel
工作吗?