Pandas数据框标题到html

jjhzyzn0  于 2023-03-06  发布在  其他
关注(0)|答案(3)|浏览(145)

无法将Pandas头单独转换为html。我有下面的代码,

df = pd.read_csv("Employees.csv")
df1= df.columns.to_frame()
df1.to_html("upload.html")

代码的结果是,

预期结果为,

无法从数据框的索引中单独获取标头。如有任何建议,将不胜感激。

yhqotfr8

yhqotfr81#

可以将headers设置为false来删除第一行,将index设置为false来删除第一列。

df1.to_html("upload.html", header=False, index=False)

剩下的是右列,您可以添加样式,使其像左列一样加粗和居中。
Documentation
希望这有帮助!

col17t5w

col17t5w2#

自定义代码生成html属性。这是更有效的,因为我们也可以添加CSS和其他html属性。

file = open("templates/upload.html", "w")
table = ["""<table border="1"> \n"""]
file.writelines(table)
file.close()

file = open("templates/upload.html", "a")
for row in list(df.columns):
    header = """<tr style="text-align: left;">\n<th>""" + row + "</th>\n</tr>\n"
    file.writelines(header)
file.close()

file = open("templates/upload.html", "a")
table = ["</table>"]
file.writelines(table)
file.close()
esbemjvw

esbemjvw3#

使用df.head(0).to_html(header=True, index=False)只获取标头。

相关问题