4

我正在使用 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)
)
4

2 回答 2

5

您可以通过执行将索引转换为object而不是datetime使用. 这是一个例子:strftime()df.index = df.index.strftime("%Y-%d-%m")

data = np.random.randn(10, 5)
index = pd.date_range('20130101', periods=10, freq='D')
pd.DataFrame(data, index=index).style.format("{:.2}")

在此处输入图像描述

pd.DataFrame(data, index=index.strftime("%Y-%m-%d")).style.format("{:.2}")

在此处输入图像描述

于 2017-10-05T15:56:03.623 回答
1

作为Pandas 1.4.0中Styler 增强功能format_index的一部分,现在可以使用直接样式化索引:

例如:

df.style.format_index(lambda s: s.strftime("%Y-%m-%d"))

风格索引

当然,这可以与其他样式链接:

(
    df.style.format_index(lambda s: s.strftime("%Y-%m-%d"))
        .format(precision=2)
        .background_gradient()
)

具有多种样式的样式化 DataFrame。 格式化索引、精度和背景梯度


设置:

import pandas as pd
from numpy.random import Generator, MT19937

rng = Generator(MT19937(10))
df = pd.DataFrame(
    rng.random(size=(10, 2)),
    index=pd.date_range('2022-01-01', periods=10, freq='D')
)

df.style

没有格式的样式器对象

于 2022-02-22T01:36:18.070 回答