Prakhar Jhudele
Prakhar Jhudele

Reputation: 955

Generate html from pandas dataframe

Pardon me I am new to handle html through pandas and having trouble generating required format

I have dataframe like below

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%

I need to generate an html like below for an email(I am also using df.styling options to format some of these fields and the)

Required format

So there are two changes I need:

  1. I need to add an header in all combined columns

  2. I need values from my category columns as header with all other columns repeated for each unique value(except date which is indexed)

Is there a way I can handle this in pandas or format my html after I generate it. I have gone through a couple of links 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 they seem to be same but a bit different

Upvotes: 0

Views: 409

Answers (1)

Danail Petrov
Danail Petrov

Reputation: 1875

To structure your data you can try this

>>> 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%



To get this into html you can simply add to_html() but this won't give you the title you need (Overall Growth Report).

To get the reop

Upvotes: 1

Related Questions