传递数据帧以生成HTML表-Python
我想生成一个HTML表,但不明白如何传递数据帧。假设df是生成html表所基于的数据帧,我想将数据帧的内容(所有td组件)传递给class函数。但是,我只得到表的标题(th)。此时我并不真正关心html样式,而是基于“df”的表格单元格 这是我的密码:传递数据帧以生成HTML表-Python,python,html,pandas,Python,Html,Pandas,我想生成一个HTML表,但不明白如何传递数据帧。假设df是生成html表所基于的数据帧,我想将数据帧的内容(所有td组件)传递给class函数。但是,我只得到表的标题(th)。此时我并不真正关心html样式,而是基于“df”的表格单元格 这是我的密码: class htmltable(): def __init__(self, _data, _cols, **kwargs): self.data = _data self.cols = _cols
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())
class htmltable():
定义初始值(自、数据、列、**kwargs):
self.data=\u数据
self.cols=\u cols
self.html=“”\
"""
对于self.cols中的col:
self.html+=“”“\
您可以参考我的以下代码:
您可以使用style.format
进行样式设置,并使用render
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())
def html_输入(c):
返回“”。格式(c)
def html_按钮(c):
返回“”。格式(c)
dict_style={}
func=[html\u输入,html\u按钮]
对于idx,枚举中的c(['id','age']):
dict_style[c]=func[idx](c)
x=df.style.format(dict_样式)
打印(x.render())
你能添加预期的HTML输出吗?这太宽泛/模糊了。堆栈溢出是针对特定的技术问题,而不是指南、教程或文档。代替c,传递rpt
,并根据需要自定义函数。