查看pandas 文档以获取to_html
.
有一个选项可以在列表中定义列间距,每列的宽度作为列表中的一个元素:
df.to_html(col_space=[20,30,140,40,40])
编辑:
对此进行更多研究,我不确定如何设置您要查找的最大列宽,但col width
通过替换生成的 html 中的文本插入,提出了一个 hack 解决方法:
.replace('<thead>','<col width="20px" />\n<col width="30px" />\n<col width="140px" />\n<col width="40px" />\n<col width="40px" />\n<thead>')
完整示例:
df = pd.DataFrame({'Group':['Short Text','Longer Text','Really Really Long Text'],
'Start Address (decimal)':['Short Text','Longer Text','Really Really Long Text'],
'Length (decimal)':['Short Text','Longer Text','Really Really Long Text'],
'Register':['Short Text','Longer Text','Really Really Long Text'],
'Bits':['Short Text','Longer Text','Really Really Long Text']})
html = df.to_html(classes=['table-bordered','table-striped','table-hover fixed'],
index=False) \
.replace('<thead>','<col width="20px" />\n<col width="30px" />\n<col width="140px" />\n<col width="40px" />\n<col width="40px" />\n<thead>')
输出
<table border="1" class="dataframe table-bordered table-striped table-hover fixed">
<col width="20px" />
<col width="30px" />
<col width="140px" />
<col width="40px" />
<col width="40px" />
<thead>
<tr style="text-align: right;">
<th>Group</th>
<th>Start Address (decimal)</th>
<th>Length (decimal)</th>
<th>Register</th>
<th>Bits</th>
</tr>
</thead>
<tbody>
<tr>
<td>Short Text</td>
<td>Short Text</td>
<td>Short Text</td>
<td>Short Text</td>
<td>Short Text</td>
</tr>
<tr>
<td>Longer Text</td>
<td>Longer Text</td>
<td>Longer Text</td>
<td>Longer Text</td>
<td>Longer Text</td>
</tr>
<tr>
<td>Really Really Long Text</td>
<td>Really Really Long Text</td>
<td>Really Really Long Text</td>
<td>Really Really Long Text</td>
<td>Really Really Long Text</td>
</tr>
</tbody>
</table>
虽然不理想,但它应该生成接近您在问题中发布的最终结果的 html。