I want to use pandas dataFrames with dataTables. I cannot figure out how to initialize the table without an id.
Is there any way to set the id in the table tag when I call df.to_html()?
I want to use pandas dataFrames with dataTables. I cannot figure out how to initialize the table without an id.
Is there any way to set the id in the table tag when I call df.to_html()?
You could try this:
It's like a SQL injection basically.
Pandas' to_html function uses double quotes around the class. You can use single quotes to define the classes argument, and put double quotes inside them to end pandas' class. Then put opening double quotes around your id name but let pandas' close those double quotes for you. The output will be the following:
Hope that helps.
Although the accepted answer works amazingly, here is what i did to apply id and also some classes to heading of tables.
This works because to_html just returns a string and we can use python replace method of string objects to replace any part with anything else( note that i used only the opening '<'). I used this to include styles to
<thead>
ie. headings section of the table!I took a sligthly different approach and decided to initialize by CSS class which had the benefit that all the pandas tables became DataTables. You can add another class if you want a more refined control with different options
I don't think this behaviour is available in
to_html
, but one way is to just insert it in manually:You could put this behaviour into a function:
Example usage:
df_to_html_with_id(df, "hello")
.