从 pandas 数据帧生成 html

Generate html from pandas dataframe

对不起,我是处理 html 到 pandas 的新手,在生成所需格式时遇到问题

我有如下数据框

Category    Date    Avg Price - growth (%)      Profit      Overall profit
A         4/18/2021      34.30%                 706.10%     669.60%
B         4/18/2021      97.40%                 1994.60%    1879.00%
C         4/18/2021      742.00%                223.60%     -482.60%

我需要为电子邮件生成如下所示的 html(我还使用 df.styling 选项来格式化其中一些字段和)

所以我需要做两个改变:

  1. 我需要在所有组合列中添加一个 header

  2. 我需要我的类别列中的值作为 header,所有其他列为每个唯一值重复(索引日期除外)

有什么方法可以在 pandas 中处理这个问题,或者在我生成它后格式化我的 html。 我浏览了几个链接

&[how-to-output-html-table-with-merged-cells-from-pandas-dataframe][3]

[3]: How to output html table with merged cells from pandas DataFrame 好像一样,但有点不同

要构建您的数据,您可以试试这个

>>> df.groupby(['Date','Category']).sum().unstack('Category').swaplevel(0,1,axis=1).sort_index(axis=1)

Category          A                                 B                                  C
          AVG_Price Overall_profit   Profit AVG_Price Overall_profit    Profit AVG_Price Overall_profit   Profit
Date
4/18/2021    34.30%        669.60%  706.10%    97.40%       1879.00%  1994.60%   742.00%       -482.60%  223.60%



要将其添加到 html 中,您只需添加 to_html() 即可,但这不会为您提供所需的标题(总体增长报告)。

获得回报