官方 文档 提供了使用 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 文件中时,单元格仍然左对齐。
如何解决这个问题?
原文由 X.X 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用 Styler 功能。
http://pandas.pydata.org/pandas-docs/stable/style.html
s.render() 返回生成的 CSS / HTML 的字符串。请注意,生成的 HTML 不会干净,因为内部为每个单元格声明了单独的样式。