Pandas DataFrame to HTML:格式化值以显示居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49903773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:29:20  来源:igfitidea点击:

Pandas DataFrame to HTML: Formatting the values to display centered

pythonhtmlpython-3.xpandasdataframe

提问by Richard Golz

I have a pandasDataFrameand am using the DataFrame.to_htmlmethod 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 HEREas well as using df.stylebefore using to_htmllike so:

我有一个pandasDataFrame并且正在使用该DataFrame.to_html方法生成一个表格,我可以在 HTML 电子邮件中发送。我只是希望某些列中的值居中,但也想知道一般如何将格式应用于表格。我曾尝试应用此处找到的文档以及在使用df.style之前使用,to_html如下所示:

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.)

将所有(或一部分)列值居中的正确方法是什么,还有哪些其他可用于格式化的选项?(例如加粗文本、更改背景或边框颜色等)

Further, at what stage should this formatting be applied? Within the to_htmlmethod or prior to it as I tried with df.style? Thanks!

此外,应该在什么阶段应用这种格式?在to_html我尝试使用的方法内或之前df.style?谢谢!

回答by Bubble Bubble Bubble Gut

I would suggest using the formatterswithin the to_htmlfunction, description of the parameter:

我建议在函数中使用格式化程序to_html,参数的描述:

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.

格式化程序:单参数函数的列表或字典,可选的格式化程序函数,用于按位置或名称应用于列元素,默认为无。每个函数的结果必须是一个 unicode 字符串。列表的长度必须等于列数。

Example if you want to make all your Namecolumn bold:

例如,如果您想让所有Name列都加粗:

df.to_html(formatters={'Name': lambda x: '<b>' + x + '</b>'})

Let me know whether it works!

让我知道它是否有效!

回答by Richard Golz

After some research and the help of Bubble Bubble Bubble Gut, this can be easily done by replacing all of the <tr>tags with <tr align="center">via:

经过一些研究和Bubble Bubble Bubble Gut的帮助,这可以通过将所有<tr>标签替换为<tr align="center">via来轻松完成:

html2 = html.replace('<tr>', '<tr align="center">')
print(html2)