The function to convert a Pandas DataFrame into an HTML <table> tag format is very useful for creating reports in web applications or embedding data in email bodies. By using the to_html method, you can instantly generate table markup without manually wrapping data in HTML tags.
This article explains the main parameters of the to_html method and how to write the output to a file or retrieve it as a string.
List of Key Parameters
The following parameters are frequently used to control the structure and attributes of the output HTML table.
| Parameter | Meaning / Role | Example Specification |
| index | Specifies whether to output row labels (index). Default is True, but set to False if not needed. | True, False |
| columns | Specifies the columns to output. Pass a list if you want to extract only specific columns. | ["Model", "Price"] |
| border | Specifies the border attribute (thickness) of the <table> tag. Note: CSS control is recommended in HTML5, but this is useful for quick checks. | 1, 2 |
| justify | Specifies the alignment of column headers. | "left", "right", "center" |
| table_id | Adds an id attribute to the <table> tag. Useful when manipulating with CSS or JavaScript. | "product_table" |
Implementation Sample Code
Below is the code showing how to output to an HTML file and retrieve an HTML string, using smartphone spec comparison data as an example.
import pandas as pd
def export_dataframe_to_html():
"""
Pandas DataFrameをHTML形式(ファイルおよび文字列)で出力する関数
"""
# 1. サンプルデータの作成
# スマートフォンのスペックリスト
smartphone_data = {
"Model": ["Phone X", "Phone Y", "Phone Z"],
"Price": [85000, 62000, 98000],
"Battery_mAh": [4500, 4000, 5000],
"Rating": [4.5, 4.2, 4.8]
}
df = pd.DataFrame(smartphone_data)
print("--- 元のDataFrame ---")
print(df)
print("\n")
# 2. 基本的なHTMLファイルへの出力
# index=False にすることで、行番号(0, 1, 2...)を除外します
basic_filename = "basic_table.html"
df.to_html(basic_filename, index=False)
print(f"基本的なHTMLファイルを出力しました: {basic_filename}")
# 3. パラメータを指定した詳細なHTML出力
# 特定の列のみ抽出し、テーブルのIDや枠線、文字配置を指定します
advanced_filename = "advanced_table.html"
df.to_html(
advanced_filename,
columns=["Model", "Price", "Rating"], # Battery_mAhを除外
index=False, # インデックスなし
table_id="price_list",# <table id="price_list">
border=2, # <table border="2">
justify="center" # ヘッダーを中央寄せ
)
print(f"詳細設定付きHTMLファイルを出力しました: {advanced_filename}")
# 4. HTML文字列として取得
# 第1引数(ファイルパス)を省略、または None を指定すると文字列が返ります
# Webフレームワーク(Flask/Django)でテンプレートに渡す際などに使用します
html_string = df.to_html(index=False, border=1)
print("\n--- 生成されたHTML文字列(抜粋) ---")
print(html_string[:150] + "...") # 長いため冒頭のみ表示
if __name__ == "__main__":
export_dataframe_to_html()
Execution Result (Console Output)
--- 元のDataFrame ---
Model Price Battery_mAh Rating
0 Phone X 85000 4500 4.5
1 Phone Y 62000 4000 4.2
2 Phone Z 98000 5000 4.8
基本的なHTMLファイルを出力しました: basic_table.html
詳細設定付きHTMLファイルを出力しました: advanced_table.html
--- 生成されたHTML文字列(抜粋) ---
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>Model</th>
<th>Price</th>
<th>Battery_mAh<...
Image of Output HTML
The content (source code) of the generated advanced_table.html looks like this. Note that only the <table> tag is output; <html> and <body> tags are not included.
<table border="2" class="dataframe" id="price_list">
<thead>
<tr style="text-align: center;">
<th>Model</th>
<th>Price</th>
<th>Rating</th>
</tr>
</thead>
<tbody>
<tr>
<td>Phone X</td>
<td>85000</td>
<td>4.5</td>
</tr>
</tbody>
</table>
Explanation
- HTML Structure:
to_htmlonly generates the table element (<table>...</table>). To display it as a complete web page, you need to embed this output inside a file that already has HTML headers. - Style Adjustment: The
borderattribute is typically deprecated in HTML5. To improve the appearance, it is common to use theclassesparameter to specify CSS classes (e.g.,classes="table table-striped") and apply designs using a CSS framework like Bootstrap.
