Export a Pandas DataFrame to Excel in Python
In this tutorial, we will learn how to export the Pandas dataframe into excel format using Python.
.to_excel() function
The pandas
library provides the in-built function named .to_excel()
which convert the pandas dataframe in excel format and save it. The function takes the input parameter as the path along with file name which refers to the location where you want to save your excel file. The other parameters are:
- sheet_name: If you want to name the sheet during the conversion of dataframe, you can pass the sheet name in this parameter. The default value is
Sheet1
. - index: You might have seen that the dataframe when printed in Python, comes along the row indices. This is often not required in the excel format. So to remove that pass
False
in the parameter. By default, the parameterTrue
is passed. - header: This refers to making the headers of dataframe as the headers of excel file too. If you don’t want and want to omit the header in excel file, pass
False
. By default, the parameterTrue
is passed.
Python Code
import pandas as pd df = pd.read_csv('data/Data.csv') df.to_excel('data/excelfile.xlsx',sheet_name="Data",index=False)
After running the above code, you will see that the dataframe has been exported in excel format successfully.
Leave a Reply