【问题标题】:Passing on data-frame to generate HTML table - Python传递数据框以生成 HTML 表 - Python
【发布时间】:2020-01-08 16:58:32
【问题描述】:

我想生成一个 HTML 表格,但不明白如何传递数据框。假设 df 是要生成 html 表的数据框,我想将数据框的内容(所有 td 组件)传递给类函数。但是,我只得到表的标题(th)。此时我并不真正关心 html 样式,而是基于“df”的表格单元格。

这是我的代码:

class htmltable():
    def __init__(self, _data, _cols, **kwargs):
        self.data = _data
        self.cols = _cols

        self.html = """\
            <table>
        """

        for col in self.cols:
            self.html += """\
            <th style="%(thstyle)sfont-size: 11px>%(thlabel)s</th>
            """ % {
                'thlabel': col['label'],
                'thstyle': col['style'] if 'style' in col else ''
                }

        self.data_dict = self.data.to_dict().values()

        super(table, self).__init__(**kwargs)

    def get_html(self):
        self.html += """</table>"""
        return self.html


df = pd.DataFrame(np.array([['John', 25, 'good'], ['Bob', 22, 'super'], ['Chris', 33, 'nice']]),
               columns=['Name', 'ID', 'Comment'])
html = df.to_html(index=false)

rpt_cols = [{'label': 'Name', 'style': 'width: 60px;'},
        {'label': 'ID'},
        {'label': 'Comment'},
        ]

rpt = table(df, rpt_cols)

print(rpt.get_html())

基本上,我想使用类将数据字典传递到 HTML 表中。使用“Class”而不是“df.to_html”的原因是因为我需要基于这个单一的数据框(df)生成各种报告。对于某些报告,某些列是不需要的;或者在其他情况下,我想有一些亮点。现在主要问题是如何获取实际的单元格内容。

【问题讨论】:

  • 你能添加预期的 HTML 输出吗?
  • 这太宽泛/模糊了。 Stack Overflow 用于特定技术问题,而不是指南、教程或文档。

标签: python html pandas


【解决方案1】:

您可以参考我的以下代码: 您可以使用style.format 进行样式设置并使用渲染。

def html_input(c):
    return '<input name="{}" type="number" step="1" min="0" max="100" value="{{}}" />'.format(c)

def html_button(c):
    return '<input name="{}" type="submit" value="{{}}" />'.format(c)

dict_style = {}
func = [html_input, html_button]
for idx, c in enumerate(['id', 'age']):
    dict_style[c] = func[idx](c)
x = df.style.format(dict_style)
print(x.render())

【讨论】:

  • 代替 c 传递 rpt 并根据您的需要自定义功能。
猜你喜欢
  • 2021-09-12
  • 2020-05-21
  • 2017-09-30
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多