【发布时间】:2020-05-28 19:11:52
【问题描述】:
考虑下面这个假人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(下面的sn-p):
<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 和Styler.to_excel 上搜索了几个问题,但似乎都关注单个元素,似乎没有解决它们的组合问题。也尝试在github上搜索问题日志,目前还没有遇到匹配。
有人有幸让set_table_styles 和Styler.to_excel 一起工作吗?
【问题讨论】:
标签: python css pandas pandas-styles