13

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()?

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52
Michael WS
  • 2,450
  • 4
  • 24
  • 46

5 Answers5

19

You could try this:

df.to_html(classes = 'my_class" id = "my_id')

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:

'<table border="1" class="dataframe my_class" id = "my_id">...'

Hope that helps.

Kevin Bishop
  • 241
  • 2
  • 3
  • 2
    That's a beautiful hack! – Private Sep 23 '15 at 15:03
  • What is my class referring to? or my ID? I do not know HTML or CSS unfortunately. I was trying to get an output of something to an Outlook email using Win32com but I can't get formatting to apply. I don't know how to create a custom class and these .styles don't seem to make it to Outlook properly. (df .style .format(percent) .applymap(color_negative_red, subset=['csat', 'fcr']) .set_properties(**{'font-size': '9pt', 'font-family': 'Calibri'}) .bar(subset=['total_hits', 'survey_count'], color='lightblue')) – trench Apr 27 '16 at 19:21
  • You'll need a basic understanding of HTML/CSS in order to fully grasp what "class" and "id" mean. Basically, classes and ids are convenient ways to apply CSS formatting only to specific parts of your html. Try this for info on classes http://www.w3schools.com/cssref/sel_class.asp Look here for the difference between class and ID http://stackoverflow.com/questions/12889362/difference-between-id-and-class-in-css-and-when-to-use-it – Kevin Bishop Apr 27 '16 at 20:46
  • What's with the weird quotes: 'my_class" id = "my_id' ? – Nic Scozzaro Apr 27 '19 at 18:29
  • Nic Scozzaro I explain it in my answer. The quotes are like when a SQL injection inserts a semicolon into a query. – Kevin Bishop Apr 28 '19 at 19:32
  • Yes +1... but note that as of pandas v0.23.0 (mid-2018), `to_html` now has a `table_id` argument, so this clever hack is not needed any more. – Owen Feb 14 '20 at 06:31
6

I don't think this behaviour is available in to_html, but one way is to just insert it in manually:

In [11]: df = pd.DataFrame([1])

In [12]: s = df.to_html()

In [13]: print (s[:7] + 'id="my_dfs_id" ' + s[7:])
<table id="my_df_id" border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>0</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>0</strong></td>
      <td> 1</td>
    </tr>
  </tbody>
</table>

You could put this behaviour into a function:

def df_to_html_with_id(df, id):
    s = df.to_html()
    return s[:7] + 'id="%s" ' % id + s[7:]

Example usage: df_to_html_with_id(df, "hello").

Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
3

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

$(document).ready(function(){
    $('.dataframe').DataTable();
});
citynorman
  • 4,918
  • 3
  • 38
  • 39
  • does this mean that you no longer need the id and somehow it knows any pd.DataFrame.to_html is a dataframe object? – tsando Jan 24 '17 at 15:03
  • @tsando: That exactly it! A slight drawback is that you might need different settings if you have many tables on your page, which you can control with the [classes paramater](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html) – citynorman Jan 24 '17 at 15:27
2

Although the accepted answer works amazingly, here is what i did to apply id and also some classes to heading of tables.

html = df.to_html().replace('<table','<table class="tableBoot" id="myTable"')

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!

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Chandan Purohit
  • 2,283
  • 1
  • 17
  • 16
0

pandas.to_html now has an argument table_id which can be used to directly set the table id.

import pandas as pd

df = pd.DataFrame({
    'A': [1, 2],
    'B': [3, 4]
})

s = df.to_html(table_id='my_df_id')
print(s)

s:

<table border="1" class="dataframe" id="my_df_id">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1</td>
      <td>3</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2</td>
      <td>4</td>
    </tr>
  </tbody>
</table>
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Daniel
  • 1