从熊猫数据帧生成 html

时间:2021-06-04 10:24:49

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

对不起,我是通过 Pandas 处理 html 的新手,并且无法生成所需的格式

我有如下所示的数据框

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 选项来格式化其中一些字段和)

Required format

所以我需要做两个改变:

  1. 我需要在所有组合列中添加标题

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

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

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

[3]: How to output html table with merged cells from pandas DataFrame 它们看起来一样但又有点不同

1 个答案:

答案 0 :(得分:1)

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

>>> 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(),但这不会为您提供所需的标题(总体增长报告)。

获取reop