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 isNone, 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'sNone.header: This boolean value shows whether the column names have to be specified or not. Its default value isTrue.index: This is the boolean value, which shows whether to show the index or not. Its default value isTrue.na_rep: This replacesNaN, 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 isNone.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 isNone.show_dimensions: When set toTrue, this will print dimensions of DataFrame. Its default value isFalse.border: This is theborder=borderattribute to apply on table tag. Its default value isNone.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 DataFrameimport pandas as pd# using DataFrame.to_html() methoddf = 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.