How to convert DataFrame to HTML using to_html()

What is pandas?

Pandas is one of the data manipulation libraries in Python, and is specifically designed for data analysis and manipulation. It offers different data structures and built-in methods to manipulate numerical data or tables.

What is to_html()?

This to_html() method from pandas.DataFrame module is used to convert a DataFrame into an HTML table.

Syntax


DataFrame.to_html(buf=None,
columns=None,
col_space=None,
header=True,
index=True,
na_rep='NaN',
max_rows=None,
max_cols=None,
border=None,
encoding=None)
Syntax

Parameters

It takes the below-mentioned parameter values.

  • buf: This is a string or StringIO-like object to write the output.
  • columns: This is a subset of columns that are going to write. The default is None, which means write all.
  • col_space: This is an integer or list-like object. It shows the column space as a pixel value. By default, it's None.
  • header: This boolean value shows whether the column names have to be specified or not. Its default value is True.
  • index: This is the boolean value, which shows whether to show the index or not. Its default value is True.
  • na_rep: This replaces NaN, that is, the string representation.
  • max_rows: This is the integer value that represents the total number of rows to print on the console. Its default value is None.
  • max_cols: This is the integer value that represents the total number of columns that are going to print on the console. Its default value is None.
  • show_dimensions: When set to True, this will print dimensions of DataFrame. Its default value is False.
  • border: This is the border=border attribute to apply on table tag. Its default value is None.
  • encoding: It shows the data encoding scheme.

Return value

If argument value buf is None, it will return converted HTML as a string otherwise None.

Code example

main.py
data.csv
# import DataFrame
import pandas as pd
# using DataFrame.to_html() method
df = pd.read_csv("data.csv")
print(df.to_html())

Code explanation

The main.py file

  • Line 4: pd.read_csv() will load "data.csv" data and return it as a DataFrame.
  • Line 5: df.to_html() will convert this data frame into HTML format.

The data.csv file

This contains a record of three different with multiple attribute values.

Free Resources