我正在使用 Pandas DataFrames 的样式属性来创建用于发送电子邮件的 HTML 表格。
我遇到的问题是我有一个日期时间索引,当我希望它显示为日期时,它显示为日期时间戳。我对时间部分不感兴趣。在解释器中,DataFrame 会正确打印出来(仅显示日期部分)。但是,当我在使用表格的样式属性进行样式化后进行渲染时,它会生成 HTML,该 HTML 也会显示时间部分。我已经研究过使用style.format()
,但我无法访问索引列。我会重置索引以使日期时间列成为普通列......但我的标题列是 MultIndex。如果我变平并且不使用索引,那么表格看起来很奇怪。
不幸的是,我在 .style 文档中发现了这一点:
限制
仅DataFrame(使用Series.to_frame().style) 索引和列必须唯一 没有大repr,性能不是很好;这适用于摘要 DataFrames 您只能设置值的样式,而不是索引或列 您只能应用样式,不能插入新的 HTML 实体 其中一些将在未来得到解决。
https://pandas.pydata.org/pandas-docs/stable/style.html#Limitations
我发帖是想看看是否有人对我如何解决这个问题有任何想法。谢谢!
显示问题的示例表: example_table_link
生成表的代码:
account_day_df = merged[['Day', 'Metric1', 'Metric2', 'Metric3', 'Metric4', 'Campaign type']]
account_day_df = account_day_df.groupby(['Day', 'Campaign type']).sum()
account_day_df.loc[:, 'Metric5'] = account_day_df['Metric1'] / account_day_df['Metric4']
account_day_df = account_day_df.unstack('Campaign type')
html += (
account_day_df.style
.background_gradient(cmap=cm, subset=['Metric5'])
.set_table_attributes('border="1" class="dataframe table table-hover table-bordered"')
.render(i)
)