如何设置熊猫的细胞对齐dataframe.to_html()
问题描述:
官方document提供了使用to_html(justify='left/right')
设置细胞对齐的选项,它可以工作。但是,目前还不清楚如何证明非标题行。如何设置熊猫的细胞对齐dataframe.to_html()
我已经使用黑客以取代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文件,单元格仍然是左对齐的。
如何解决这一问题?
答
您可以使用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将不会干净,因为内部为每个单元格声明了单独的样式。
更全面的设置请参阅http://*.com/a/40993135/2944092中的答案 –