【问题标题】:pandas style set_table_styles for columns/index does not work with to_excel列/索引的熊猫样式 set_table_styles 不适用于 to_excel
【发布时间】: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() 似乎确认样式已应用于thtd(下面的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')

我尝试将 xlsxwriteropenpyxl 作为引擎,两者都表现出相同的行为。

我在set_table_stylesStyler.to_excel 上搜索了几个问题,但似乎都关注单个元素,似乎没有解决它们的组合问题。也尝试在github上搜索问题日志,目前还没有遇到匹配。

有人有幸让set_table_stylesStyler.to_excel 一起工作吗?

【问题讨论】:

    标签: python css pandas pandas-styles


    【解决方案1】:

    这似乎是当前版本中仍然存在的错误 (1.0.3)。我在他们的仓库中提出了一个错误:https://github.com/pandas-dev/pandas/issues/34438

    解决后会尝试更新...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 2014-04-01
      • 2017-02-20
      • 1970-01-01
      • 2018-05-03
      相关资源
      最近更新 更多