将Pandas DataFrame转换为HTML:格式化值以使其居中显示 [英] Pandas DataFrame to HTML: Formatting the values to display centered
问题描述
我有一个熊猫
DataFrame
,并且正在使用 DataFrame.to_html
方法生成可以在HTML电子邮件中发送的表。我只是想将某些列中的值居中,但也想了解一般如何将格式应用于表。我尝试应用发现的文档这里以及在使用 to_html
之前使用 df.style
,例如:
I have a pandas
DataFrame
and am using the DataFrame.to_html
method to generate a table I can send within an HTML email message. I simply want the values in certain columns to be centered, but would also like to know in general how to apply formatting to the table. I have tried applying the documentation found HERE as well as using df.style
before using to_html
like so:
df.style.set_properties(**{'text-align':'center'})
但我仍将所有值左对齐(标题中间的标题除外)。
But i am still getting all of my values left-aligned (other than the headers, which are centered).
将所有(或子集)列值居中的正确方法是什么,还有其他可用于格式化的选项吗? (例如,加粗文本,更改背景或边框颜色等)
What is the correct way to center all (or a subset) of my column values, and what are the other options available for formatting? (e.g. bolding text, changing background or border colors, etc.)
此外,应在什么阶段应用此格式?在 to_html
方法中还是在我尝试使用 df.style
之前?谢谢!
Further, at what stage should this formatting be applied? Within the to_html
method or prior to it as I tried with df.style
? Thanks!
推荐答案
我建议在 to_html <中使用格式化程序 / code>函数,参数说明:
I would suggest using the formatters within the to_html
function, description of the parameter:
formatters :一个或-参数函数,可选的格式化程序函数,用于按位置或名称应用于列的元素,
默认为无。每个函数的结果必须是一个unicode字符串。
列表的长度必须等于列数。
formatters : list or dict of one-parameter functions, optional formatter functions to apply to columns’ elements by position or name, default None. The result of each function must be a unicode string. List must be of length equal to the number of columns.
例如,如果要使所有名称
列粗体:
Example if you want to make all your Name
column bold:
df.to_html(formatters={'Name': lambda x: '<b>' + x + '</b>'})
我知道它是否有效!
这篇关于将Pandas DataFrame转换为HTML:格式化值以使其居中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!