JS dataTables from pandas

2019-01-23 15:22发布

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

4条回答
叛逆
2楼-- · 2019-01-23 15:45

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.

查看更多
迷人小祖宗
3楼-- · 2019-01-23 15:46

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!

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-23 15:48

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();
});
查看更多
Explosion°爆炸
5楼-- · 2019-01-23 16:05

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

查看更多
登录 后发表回答