I would like to define a css id to a Pandas Dataframe to render with javascript dataTables. Is it possible?
With this:
pandas.DataFrame([[1, 2], [3, 4]]).to_html()
I get this:
'<table border="1" class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>0</th>\n <th>1</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>1</td>\n <td>2</td>\n </tr>\n <tr>\n <th>1</th>\n <td>3</td>\n <td>4</td>\n </tr>\n </tbody>\n</table>'
But I'd like to get a css id, like this:
'<table border="1" id='mytable' class="dataframe">\n <thead>\n <tr style="text-align: right;">\n <th></th>\n <th>0</th>\n <th>1</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>1</td>\n <td>2</td>\n </tr>\n <tr>\n <th>1</th>\n <td>3</td>\n <td>4</td>\n </tr>\n </tbody>\n</table>'
To use dataTables in my html page:
$(document).ready(function() {
$('#mytable').DataTable();
});
just use pandas.DataFrame([[1, 2], [3, 4]]).to_html(table_id='hello')
you will set table id namely hello
There is a lot of things you can do with the DataFrame.to_html() method in pandas 0.16, but there is currently no documented way to add an id to the rendered dataframe.
You can set a class on the DataFrame, like this:
df = pd.DataFrame({'foo':[1,2,3,4]})
df.to_html(classes='mytable')
Results in:
<table border="1" class="dataframe mytable">
...
But that is as good as it gets with pandas native functions.
If you really need to use the css id option, you could solve it in two ways.
The proper way would be to parse the html using a library for xml parsing and adding the id yourself.
Something like this:
from xml.etree import ElementTree as et
t = et.fromstring(df.to_html())
t.set('id', 'mytable')
et.tostring(t)
Results in:
<table border="1" class="dataframe" id="mytable">
...
There are other libraries than the xml library, you could for instance use BeautifulSoup to change the html. The BeautifulSoup library has more shiny features that lets you do more complicated stuff than just setting and id on the table.
The ugly way would be to regexp replace the string, like this:
import re
re.sub(' mytable', '" id="mytable', df.to_html(classes='mytable'))
Results in:
<table border="1" class="dataframe" id="mytable">
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With