JS dataTables from pandas

前端 未结 4 1841
挽巷
挽巷 2020-12-15 23:14

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 w

相关标签:
4条回答
  • 2020-12-16 00:06

    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.

    0 讨论(0)
  • 2020-12-16 00:08

    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!

    0 讨论(0)
  • 2020-12-16 00:14

    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();
    });
    
    0 讨论(0)
  • 2020-12-16 00:18

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

    0 讨论(0)
提交回复
热议问题