如何将表id注入pandas.DataFrame.to_html()输出?

问题描述 投票:0回答:4

使用以下python代码从pandas DataFrame生成HTML表:

在:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.zeros((2,2)))
df.to_html()
print(df.to_html())

OUT:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>0</th>
      <th>1</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>0.0</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>1</th>
      <td>0.0</td>
      <td>0.0</td>
    </tr>
  </tbody>
</table>

有没有一种简单的方法可以将id插入表格开始标记?

这样开始标记看起来像这样:

<table id="my_table" border="1" class="dataframe">
python html pandas dataframe
4个回答
1
投票

您可以使用BeautifulSoup将id属性添加到表中:

from bs4 import BeautifulSoup
soup = BeautifulSoup(df.to_html(), "html.parser")    
soup.find('table')['id'] = 'my_table'
soup

<table border="1" class="dataframe" id="my_table">
    <thead>
        <tr style="text-align: right;">
            <th></th>
            <th>0</th>
            <th>1</th>
...

要将html作为str,请使用str(soup)


2
投票

我试过这个:

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

我得到以下内容:

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

我在这里找到了:https://code.i-harness.com/en/q/1d2d2af


1
投票

最简单的方法是使用Styler接口生成HTML,它可以设置任意表属性(set_table_attributes)。生成的HTML更加冗长,因为嵌入了许多扩展ID /类,但应该等效地呈现。

print(df.style.set_table_attributes('id="my_table"').render())


<style  type="text/css" >
</style>  
<table id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856a" id="my_table"> 
<thead>    <tr> 
        <th class="blank level0" ></th> 
        <th class="col_heading level0 col0" >0</th> 
        <th class="col_heading level0 col1" >1</th> 
    </tr></thead> 
<tbody>    <tr> 
        <th id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856a" class="row_heading level0 row0" >0</th> 
        <td id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow0_col0" class="data row0 col0" >0</td> 
        <td id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow0_col1" class="data row0 col1" >0</td> 
    </tr>    <tr> 
        <th id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856a" class="row_heading level0 row1" >1</th> 
        <td id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow1_col0" class="data row1 col0" >0</td> 
        <td id="T_6ebfc734_51f7_11e7_b81e_b808cf3e856arow1_col1" class="data row1 col1" >0</td> 
    </tr></tbody> 
</table> 

0
投票

最简单的方法是从我在Pandas文档中找到的片段并使用Pandas

df.to_html( table_id = "t01")

输出:

<table id = "my_id">

资料来源:https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.to_html.html

© www.soinside.com 2019 - 2024. All rights reserved.