Skip to main content
 首页 » 编程设计

python之Pandas DataFrame 到 HTML : Formatting the values to display centered

2025年05月04日22zhengyun_ustc

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

df.style.set_properties(**{'text-align':'center'}) 

但我仍然让所有值左对齐(标题除外,它们居中)。

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

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

请您参考如下方法:

我建议在to_html 函数中使用formatters,参数说明:

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.

如果您想将所有 Name 列设为粗体的示例:

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

让我知道它是否有效!