如何在 Pandas dataframe.to_html() 中设置单元格对齐方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40187056/
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 02:16:13  来源:igfitidea点击:

How to set cell alignment in pandas dataframe.to_html()

htmlpandashtml-tablejustify

提问by X.X

The official documentprovided options to set cell alignment using to_html(justify='left/right')and it works. However, it is not clear how to justify non-header rows.

官方文档提供了使用设置单元格对齐的选项to_html(justify='left/right')并且它有效。但是,尚不清楚如何证明非标题行的合理性。

I've to use a hack to replace the HTML part

我必须使用 hack 来替换 HTML 部分

import pandas as pd
df = pd.DataFrame({'looooong_col':['1,234','234,567','3,456,789'],'short_col':[123,4,56]})
raw_html = df.to_html()
raw_html.replace('<tr>','<tr style="text-align: right;">')

So the modified html now is

所以修改后的html现在是

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>looooong_col</th>
      <th>short_col</th>
    </tr>
  </thead>
  <tbody>
    <tr style="text-align: right;">
      <th>0</th>
      <td>1,234</td>
      <td>123</td>
    </tr>
    <tr style="text-align: right;">
      <th>1</th>
      <td>234,567</td>
      <td>4</td>
    </tr>
    <tr style="text-align: right;">
      <th>2</th>
      <td>3,456,789</td>
      <td>56</td>
    </tr>
  </tbody>
</table>

and it rendered ok in http://htmledit.squarefree.com/but not when I write it out to a html file, the cells are still left-justified.

它在http://htmledit.squarefree.com/ 中呈现正常,但当我将其写入 html 文件时,单元格仍然左对齐。

How to fix this?

如何解决这个问题?

回答by ashishsingal

You can use the Styler functionality.

您可以使用样式器功能。

http://pandas.pydata.org/pandas-docs/stable/style.html

http://pandas.pydata.org/pandas-docs/stable/style.html

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(6,4),columns=list('ABCD'))
s = df.style.set_properties(**{'text-align': 'right'})
s.render()

s.render() returns a string of the generated CSS / HTML. Note the generated HTML will not be clean, as the internals declare a separate style for each cell.

s.render() 返回生成的 CSS / HTML 的字符串。请注意,生成的 HTML 不会是干净的,因为内部为每个单元格声明了一个单独的样式。

回答by ProsperousHeart

You may want to try to do the styling outside in the CSS instead.

您可能想尝试在 CSS 外部进行样式设置。

If you're using MultiIndexyou will be unable to use Styler.

如果您使用MultiIndex,您将无法使用 Styler。

For example, you could add the following before your table HTML:

例如,您可以在表格 HTML 之前添加以下内容:

<style>
table {text-align: center;}
table thead th {text-align: center;}
</style>

回答by anish

This did the trick for me

这对我有用

df.to_html(justify='left')