【问题标题】:Pandas datatable to html with footerPandas 数据表到带有页脚的 html
【发布时间】:2020-10-23 15:22:54
【问题描述】:

假设我将以下数据输出到 HTML 为:

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

我希望它也能生成页脚信息,例如在末尾的 </tbody> 标记之后。

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

https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.to_html.html 此处的文档没有建议页脚选项,所以想知道是否有解决方法?

许多表是动态生成的,因此硬编码是不可行的。

感谢您的任何建议

【问题讨论】:

  • 在 to_html 中似乎不支持。为什么不使用像 lxml 这样的 dom 解析器来创建页脚元素并将其插入到表格中?

标签: python html pandas


【解决方案1】:

df.to_html 返回一个 str,因此您可以手动添加它。

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

输出

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

【讨论】:

    猜你喜欢
    • 2012-06-24
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2019-01-08
    • 1970-01-01
    相关资源
    最近更新 更多