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

6 Answers 6

18

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.

Sign up to request clarification or add additional context in comments.

6 Comments

That's a beautiful hack!
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'))
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 w3schools.com/cssref/sel_class.asp Look here for the difference between class and ID stackoverflow.com/questions/12889362/…
What's with the weird quotes: 'my_class" id = "my_id' ?
Nic Scozzaro I explain it in my answer. The quotes are like when a SQL injection inserts a semicolon into a query.
|
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").

Comments

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();
});

2 Comments

does this mean that you no longer need the id and somehow it knows any pd.DataFrame.to_html is a dataframe object?
@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
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!

Comments

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>

Comments

0

maybe you can try In python: dt = [your dataframe].to_json(orient="split")

In js: use DataTable from jquery

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.