Ale*_*ias 4 html python formatting pandas
我正在使用 Pandas DataFrames 的 style 属性来创建用于发送电子邮件的 HTML 表格。我遇到的问题是我有一个日期时间索引,当我希望它显示为日期时,它显示为日期时间戳。我对时间部分不感兴趣。在解释器中,数据框确实打印出来(只显示日期部分)。但是当我使用表格的 style 属性进行样式化后渲染时,它会生成 HTML 并显示时间部分。我已经研究过使用 style.format() 但我无法访问索引列。我会重置索引以使日期时间列成为普通列......但我的标题列是多重索引。如果我变平并且不使用索引,则表格看起来很奇怪。
不幸的是,我在 .style 文档中发现了这一点:
限制
DataFrame only (use 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)
)
Run Code Online (Sandbox Code Playgroud)
作为pandas 1.4.0 中Styler 增强功能的一部分,format_index现在可以直接使用索引设置样式:
例如:
df.style.format_index(lambda s: s.strftime("%Y-%m-%d"))
Run Code Online (Sandbox Code Playgroud)
当然,这可以与其他样式链接:
(
df.style.format_index(lambda s: s.strftime("%Y-%m-%d"))
.format(precision=2)
.background_gradient()
)
Run Code Online (Sandbox Code Playgroud)
设置:
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
Run Code Online (Sandbox Code Playgroud)
小智 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}")
Run Code Online (Sandbox Code Playgroud)
pd.DataFrame(data, index=index.strftime("%Y-%m-%d")).style.format("{:.2}")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3373 次 |
| 最近记录: |