Home » Tutorials » Python Tutorials » Python – Render Pandas DataFrame as HTML Table?

Python – Render Pandas DataFrame as HTML Table?

In this article we will learn How to Render Pandas DataFrame as HTML Table?

Pandas in Python has the ability to convert Pandas DataFrame to a table in the HTML web page. pandas.DataFrame.to_html()  method is used for render a Pandas DataFrame.

Syntax : DataFrame.to_html()
Return : Return the html format of a dataframe.

Let’s understand with examples:

First, Create a DataFrame:

# importing pandas as pd
import pandas as pd
from IPython.display import HTML
# creating the dataframe
df = pd.DataFrame({"Name": ['Anurag', 'Manjeet', 'Shubham',
'Saurabh', 'Ujjawal'],
"Address": ['Patna', 'Delhi', 'Coimbatore',
'Greater noida', 'Patna'],
"ID": [20123, 20124, 20145, 20146, 20147],
"Sell": [140000, 300000, 600000, 200000, 600000]})
print("Original DataFrame :")
display(df)

How to Render Pandas DataFrame as HTML Table? - myTechMint

Convert Dataframe to Html Table:

result = df.to_html()
print(result)

Output:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Name</th>
      <th>Address</th>
      <th>ID</th>
      <th>Sell</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>Anurag</td>
      <td>Patna</td>
      <td>20123</td>
      <td>140000</td>
    </tr>
    <tr>
      <th>1</th>
      <td>Manjeet</td>
      <td>Delhi</td>
      <td>20124</td>
      <td>300000</td>
    </tr>
    <tr>
      <th>2</th>
      <td>Shubham</td>
      <td>Coimbatore</td>
      <td>20145</td>
      <td>600000</td>
    </tr>
    <tr>
      <th>3</th>
      <td>Saurabh</td>
      <td>Greater noida</td>
      <td>20146</td>
      <td>200000</td>
    </tr>
    <tr>
      <th>4</th>
      <td>Ujjawal</td>
      <td>Patna</td>
      <td>20147</td>
      <td>600000</td>
    </tr>
  </tbody>
</table>

Write a Script to Convert DataFrame into HTML File:

html = df.to_html()
# write html to file
text_file = open("index.html", "w")
text_file.write(html)
text_file.close()

Note: The HTML file will be created with HTML data in the current working directory.

Output:

Write a Script to Convert DataFrame into HTML File

 

Related:  Python - Convert String to DateTime and Vice-Versa

Display HTML Data in the Form of a Table-Striped:

HTML(df.to_html(classes='table table-striped'))

Display HTML Data in the Form of a Table-Striped.

 

Leave a Comment