使用以下python代码从pandas DataFrame生成HTML表:
在:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.zeros((2,2)))
df.to_html()
print(df.to_html())
OUT:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>0</th>
<th>1</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0.0</td>
<td>0.0</td>
</tr>
<tr>
<th>1</th>
<td>0.0</td>
<td>0.0</td>
</tr>
</tbody>
</table>
是否有一种简单的方法可以将id
插入表格开始标记?
这样开始标记如下所示:
<table id="my_table" border="1" class="dataframe">
答案 0 :(得分:2)
我尝试过:
df.to_html(classes = 'my_class" id = "my_id')
我得到以下信息:
<table border="1" class="dataframe my_class" id = "my_id">
答案 1 :(得分:1)
最简单的方法是使用Styler
接口生成HTML,这可以设置任意表属性(set_table_attributes
)。生成的HTML更加冗长,因为嵌入了许多扩展ID /类,但应该等效地呈现。
print(df.style.set_table_attributes('id="my_table"').render())
<style type="text/css" >
</style>
<table id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856a" id="my_table">
<thead> <tr>
<th class="blank level0" ></th>
<th class="col_heading level0 col0" >0</th>
<th class="col_heading level0 col1" >1</th>
</tr></thead>
<tbody> <tr>
<th id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856a" class="row_heading level0 row0" >0</th>
<td id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow0_col0" class="data row0 col0" >0</td>
<td id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow0_col1" class="data row0 col1" >0</td>
</tr> <tr>
<th id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856a" class="row_heading level0 row1" >1</th>
<td id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow1_col0" class="data row1 col0" >0</td>
<td id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow1_col1" class="data row1 col1" >0</td>
</tr></tbody>
</table>
答案 2 :(得分:1)
您可以使用 BeautifulSoup 向表中添加id
属性:
from bs4 import BeautifulSoup
soup = BeautifulSoup(df.to_html(), "html.parser")
soup.find('table')['id'] = 'my_table'
soup
<table border="1" class="dataframe" id="my_table">
<thead>
<tr style="text-align: right;">
<th></th>
<th>0</th>
<th>1</th>
...
要将html设为str,请使用str(soup)
。
答案 3 :(得分:0)
最简单的方法是从我在熊猫文档中找到并使用熊猫的代码段
df.to_html( table_id = "t01")
输出:
<table id = "my_id">
来源:https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.to_html.html
答案 4 :(得分:0)
这是在将数据帧转换为HTML的过程中获取插入id /类的正确方法:
df.to_html(classes = 'class1', table_id = 'id_tab')
如果我们要包含多个类,我们可以分配一个类列表,例如:
df.to_html(classes = ['class1', 'class2'], table_id = 'id_tab')
可用的详细信息here。