【问题标题】:How to set cell alignment in pandas dataframe.to_html()如何在 pandas dataframe.to_html() 中设置单元格对齐
【发布时间】:2017-03-04 09:06:33
【问题描述】:

官方document 提供了使用to_html(justify='left/right') 设置单元格对齐的选项,并且可以正常工作。但是,尚不清楚如何证明非标题行的合理性。

我必须使用 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;">')

所以现在修改后的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>

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

如何解决这个问题?

【问题讨论】:

标签: html pandas html-table justify


【解决方案1】:

您可以使用 Styler 功能。

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() 返回生成的 CSS / HTML 的字符串。请注意,生成的 HTML 将不干净,因为内部为每个单元格声明了单独的样式。

【讨论】:

【解决方案2】:

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

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

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

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

【讨论】:

    【解决方案3】:

    这对我有用

    df.to_html(justify='left')
    

    【讨论】:

    • df.to_html(justify='left'),如原始问题所述,仅适用于列标题,而不适用于数据框的其余部分。
    【解决方案4】:

    要居中对齐列中的所有值,这对我有用

    dict(selector="td", props=[("text-align", "center")])
    

    【讨论】:

      【解决方案5】:

      我知道这是一个老问题,我注意到您问的是当您的数字是字符串格式时如何执行此操作,即 ['1,234','234,567','3,456,789']

      但是,如果您在 pandas 数据框中只有浮点数或浮点数和字符串的混合,那么一种方法就是

      df.to_html().replace('<td>', '<td align="right">')
      

      我个人需要这样做,因为我有以下格式,我想摆脱上面的过程:

      pd.options.display.float_format = '{:,.0f}'.format
      df.to_html().replace('<td>', '<td align="right">')
      

      完美地完成了这项工作,并且不会像使用 Sty 那样弄乱我的格式

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-15
        • 2021-11-14
        • 1970-01-01
        • 1970-01-01
        • 2015-07-29
        • 2022-01-15
        • 2016-09-23
        • 2011-03-01
        相关资源
        最近更新 更多