2017-06-15 12 views
0

pandas.DataFrame.to_html()の出力にテーブルIDを挿入する方法は?パンダのデータフレームからHTMLテーブルを生成するために、次のPythonのコードを使用して

の場合:

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

答えて

1

あなたは、テーブルにid属性を追加するBeautifulSoupを使用することができます。

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

strのようなHTMLを取得するには、str(soup)を使用しています。

1

これを行う最も簡単な方法は、任意のテーブルのプロパティ(set_table_attributes)を設定することができますHTMLを生成するためのStylerインタフェースを使用することです。生成された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> 
関連する問題