14.7 C
London
Tuesday, July 2, 2024
HomePandas in PythonInput/Output in PythonHow to Export a Pandas DataFrame to Excel

How to Export a Pandas DataFrame to Excel

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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.

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories