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

标签 python html python-3.x pandas dataframe

我有一个 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>'})

让我知道它是否有效!

关于python - Pandas DataFrame 到 HTML : Formatting the values to display centered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49903773/

相关文章:

python - if 语句的语法无效

python - python 3.6.5 中的 pygame 中没有显示图像

python - 包含要使用 python 保存在 Excel 中的值列表的变量

python - 如何解决在 Flask Web 服务器中使用 Pyomo 时出现错误?

javascript - 如何在 html 页面之间设置自定义预加载器?

javascript - 无法将变量数据提取为字符串格式以传递给数据库

javascript - 我如何从客户端(html)拍照并将其保存到服务器端(Python)

python - 类似于 Pylons for Ruby 的框架

javascript - 单击时 HTML 下拉菜单不会保持打开状态

python - 将参数传递给 PyRun_File(***)