How To Inject A Table Id Into Pandas.dataframe.to_html() Output?
Solution 1:
I tried this:
df.to_html(classes = 'my_class" id = "my_id')
and I got the following:
<table border="1"class="dataframe my_class"id = "my_id">
I found it here: https://code.i-harness.com/en/q/1d2d2af
Solution 2:
You can use BeautifulSoup to add an id
attribute to the table:
from bs4 importBeautifulSoup
soup = BeautifulSoup(df.to_html(), "html.parser")
soup.find('table')['id'] = 'my_table'
soup
<table border="1"class="dataframe" id="my_table">
<thead>
<trstyle="text-align: right;"><th></th><th>0</th><th>1</th>
...
To get the html as str, use str(soup)
.
Solution 3:
The easiest way to do this is to use the Styler
interface for generating HTML, which can set arbitrary table properties (set_table_attributes
). The resulting HTML is more verbose, because there are a number of extension ids/classes embedded, but should render equivalently.
print(df.style.set_table_attributes('id="my_table"').render())
<styletype="text/css" ></style><tableid="T_6ebfc734_51f7_11e7_b81e_b808cf3e856a"id="my_table"><thead><tr><thclass="blank level0" ></th><thclass="col_heading level0 col0" >0</th><thclass="col_heading level0 col1" >1</th></tr></thead><tbody><tr><thid="T_6ebfc734_51f7_11e7_b81e_b808cf3e856a"class="row_heading level0 row0" >0</th><tdid="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow0_col0"class="data row0 col0" >0</td><tdid="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow0_col1"class="data row0 col1" >0</td></tr><tr><thid="T_6ebfc734_51f7_11e7_b81e_b808cf3e856a"class="row_heading level0 row1" >1</th><tdid="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow1_col0"class="data row1 col0" >0</td><tdid="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow1_col1"class="data row1 col1" >0</td></tr></tbody></table>
Solution 4:
The easiest way is from the snippet I found in the Pandas Documents and uses Pandas
df.to_html( table_id = "my_id")
Output:
<table id = "my_id">
Source: https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.to_html.html
Solution 5:
This is the correct way to get id / class inserted during dataframe conversion to HTML:
df.to_html(classes = 'class1', table_id = 'id_tab')
In case we want to include multiple classes, we may assign a list of classes like:
df.to_html(classes = ['class1', 'class2'], table_id = 'id_tab')
Detailed information available here.
Post a Comment for "How To Inject A Table Id Into Pandas.dataframe.to_html() Output?"