Pandas datatable to html with footer

Viewed 513

Suppose I output the following data to HTML as:

import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df.to_html(index = False, header = "true")

What I would like is for this to also produce footer information, something like after the </tbody> tag at the end.

<tfoot>\n     <th>col1</th>\n      <th>col2</th>\n    </tr>\n  </tfoot>

The documentation here https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.to_html.html doesn't suggest a footer option, so curious if there is a workaround?

Many tables are dynamically produced on the fly so hardcoding wouldn't be feasible.

Thanks for any suggestions

1 Answers

df.to_html return a str so you can just add it manually.

import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
df.to_html(index = False, header = "true")\
+"<tfoot>\n" + " ".join(["<th>"+ i +"</th>\n" for i in df.columns])+"</tr>\n  </tfoot>"

ouput

'<table border="1" class="dataframe">\n  <thead>\n    <tr style="text-align: right;">\n      <th>col1</th>\n      <th>col2</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>1</td>\n      <td>3</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>4</td>\n    </tr>\n  </tbody>\n</table><tfoot>\n<th>col1</th>\n <th>col2</th>\n</tr>\n  </tfoot>'
Related