python · March 26, 2023 0

How to Convert Pandas Dataframes to HTML Tables in Python

Table of Content

To convert a Pandas Dataframe to an HTML table in Python, you can use the to_html() method provided by the Pandas library. Here is an example code snippet:

import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'Name': ['John', 'Mary', 'Mark'], 'Age': [25, 30, 35], 'City': ['New York', 'London', 'Paris']})

# convert dataframe to HTML table
html_table = df.to_html()

# print the HTML table

In this example, we first create a Pandas DataFrame and then convert it to an HTML table using the to_html() method. The resulting HTML table is then stored in the html_table variable, and we print it using the print() function.

Note that the to_html() method provides a number of options to customize the HTML table, such as setting the table class or applying custom formatting to the cells.

Also note that the resulting HTML table may require additional styling or formatting to look good on a web page. You can use CSS or other tools to customize the appearance of the HTML table as needed.

%d bloggers like this: