【问题标题】:Pandas styling with Python使用 Python 进行 Pandas 样式设置
【发布时间】:2020-05-05 15:51:29
【问题描述】:

我对@9​​87654321@ 很陌生,并尝试将我的Pandas DataFramecolour 设置为headers grey colour,这是我的尝试:

with open ('test.html','w') as test:
    test, df.style.set_properties(**{'text-align': 'center'}).set_table_styles([ dict(selector='th', props=[('text-align', 'center')] ) ]).render()

有2个问题和1个问题:

问题

1 - 像excel 一样为headers grey 着色

2 - 导出为HTML

问题: 是否也可以将完成的样式呈现为 excel 文件?

【问题讨论】:

  • 您要导出为HTML 还是excel
  • 先HTML,然后如果可以导出excel。

标签: python css python-3.x pandas styles


【解决方案1】:

是的,你可以这样做:

def hover(hover_color="#ffff99"):
    return dict(selector="tr:hover",
                props=[("background-color", "%s" % hover_color)])
styles = [
    hover(),
    dict(selector='thead', props=[('background-color','grey')]),
]

# this forces grey background on header
styler = df.style.set_table_styles(styles)

# HTML string
html = styler.render()

# save html
with open('file.html', 'w') as f:
    f.write(html)

# excel
styler.to_excel('file.xlsx')

【讨论】:

  • 谢谢,excel 标题没有着色。而且我没有看到生成的 HTML 文件。我想要 HTML 文件?
  • @Pythonista 你是对的,excel 文件仍然没有灰色标题。请参阅html 保存的更新。
猜你喜欢
  • 1970-01-01
  • 2021-09-25
  • 2011-08-17
  • 2012-11-27
  • 1970-01-01
  • 2021-09-05
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多