Often you may be interested in exporting a pandas DataFrame to Excel. Fortunately this is easy to do using the pandas to_excel() function.
In order to use this function, you’ll need to first install openpyxl so that you’re able to write files to Excel:
pip install openpyxl
This tutorial will explain several examples of how to use this function with the following DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame({'points': [25, 12, 15, 14, 19], 'assists': [5, 7, 7, 9, 12], 'rebounds': [11, 8, 10, 6, 6]}) #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6
Example 1: Basic Export
The following code shows how to export the DataFrame to a specific file path and save it as mydata.xlsx:
df.to_excel(r'C:UsersZachDesktopmydata.xlsx')
Here’s what the actual Excel file looks like:
Example 2: Export without Index
The following code shows how to export the DataFrame to a specific file path and remove the index column:
df.to_excel(r'C:UsersZachDesktopmydata.xlsx', index=False)
Here’s what the actual Excel file looks like:
Example 3: Export without Index and Header
The following code shows how to export the DataFrame to a specific file path and remove the index column and the header row:
df.to_excel(r'C:UsersZachDesktopmydata.xlsx', index=False, header=False)
Here’s what the actual Excel file looks like:
Example 4: Export and Name the Sheet
The following code shows how to export the DataFrame to a specific file path and name the Excel worksheet:
df.to_excel(r'C:UsersZachDesktopmydata.xlsx', sheet_name='this_data')
Here’s what the actual Excel file looks like:
You can find the complete documentation for the to_excel() function here.