繁体   English   中英

如何将表 ID 注入到 pandas.DataFrame.to_html() 输出中?

[英]How to inject a table id into pandas.DataFrame.to_html() output?

使用以下 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())

出去:

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

我试过这个:

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

您可以使用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)

最简单的方法是使用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> 

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

df.to_html( table_id = "my_id")

输出:

<table id = "my_id">

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

这是在数据帧转换为 HTML 期间插入 id/class 的正确方法:

df.to_html(classes = 'class1', table_id = 'id_tab')    

如果我们想包含多个类,我们可以分配一个类列表,如:

df.to_html(classes = ['class1', 'class2'], table_id = 'id_tab')

此处提供详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM