Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define html id for Pandas Dataframe

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();
});
like image 801
msampaio Avatar asked Jun 02 '15 10:06

msampaio


2 Answers

just use pandas.DataFrame([[1, 2], [3, 4]]).to_html(table_id='hello') you will set table id namely hello

like image 79
Durgesh Kumar Avatar answered Oct 23 '22 07:10

Durgesh Kumar


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.

Proper but slow solution

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">
...

Addendum:

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.

Hacky but performative solution

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">
...
like image 41
firelynx Avatar answered Oct 23 '22 07:10

firelynx