How do you export a Pandas DataFrame to an Excel file? It’s very easy to do. This exercise might become very important if you are coding in Python and you need to export your result to Excel so that you can display the results in Excel or import the data into Tableau.
I will test it by creating a project in Jupyter Notebook with Anaconda Navigator.
# import pandas import pandas as pd # manually create a DataFrame import pandas as pd # import the pandas library into Python data = {'firstname': ['Bob', 'Sally', 'Suzie', 'Rowan'], 'amount': [12, 67, 33, 41]} df = pd.DataFrame(data) df
Here is what Jupyter Notebook shows.
Now we want to export our data to an Excel file. We’ll use the pandas function to_excel().
# specify the name of the file file_name = 'D:\Test\People.xlsx' # saving the excel file df.to_excel(file_name) print('DataFrame is written to Excel File successfully.')
It’s possible to get errors here. For example, if the folder Test does not exist, the Excel file will not be written.
To write a single object to an Excel .xlsx file it is only necessary to specify a target file name. To write to multiple sheets it is necessary to create an ExcelWriter object with a target file name, and specify a sheet in the file to write to.
For more information try GeeksForGeeks Exporting a Pandas DataFrame to an Excel file.