Pandas DataFrame as HTML Table Example
Let’s understand with an example of Styler Object and HTML in Pandas step-by-step.
Step 1: Create a Dataframe
In this example, code uses pandas to create a Pandas DataFrame with details about individuals, such as names, addresses, IDs, and sales. It then prints the original DataFrame in a tabular format using the IPython display function.
Python3
# 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) |
Output:
Original DataFrame :
Name Address ID Sell
0 Anurag Patna 20123 140000
1 Manjeet Delhi 20124 300000
2 Shubham Coimbatore 20145 600000
3 Saurabh Greater noida 20146 200000
4 Ujjawal Patna 20147 600000
Step 2: Convert Dataframe to Html Table
Here , the code generates an HTML table representation of the DataFrame ‘df’ using to_html and prints the HTML result.
Python3
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>
Step 3: Write the Script For Convert DataFrame into HTML File
In this example code converts the DataFrame ‘df’ into an HTML table (‘html’) and writes it to an “index.html” file, creating a static HTML page containing the DataFrame representation.
Python3
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:
Step 4: Display HTML Data in the Form of a Table-Stripped
Here code applies Bootstrap styling classes to the DataFrame ‘df’ when converting it to an HTML table, enhancing its visual appearance with striped rows.
Python3
HTML(df.to_html(classes = 'table table-stripped' )) |
Output:
How to render Pandas DataFrame as HTML Table?
Pandas in Python can convert Pandas DataFrame to a table in the HTML web page. pandas.DataFrame.to_html() method is used to render a Pandas DataFrame. In this article, we will understand how to Styler Object and HTML in Pandas.
Pandas DataFrame as HTML Table Syntax
Syntax: DataFrame.to_html()
Return : Return the html format of a dataframe.