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:
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:
Convert Dataframe to Html table:
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>
Let write the script for convert DataFrame into HTML file:
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:
Let’s display HTML data in the form of a table-stripped
Python3
HTML(df.to_html(classes = 'table table-stripped' )) |
Output: