2.4 C
London
Friday, December 20, 2024
HomePandas in PythonInput/Output in PythonHow to Export Pandas DataFrame to CSV (With Example)

How to Export Pandas DataFrame to CSV (With Example)

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...

You can use the following syntax to export a pandas DataFrame to a CSV file:

df.to_csv(r'C:UsersBobDesktopmy_data.csv', index=False)

Note that index=False tells Python to drop the index column when exporting the DataFrame. Feel free to drop this argument if you’d like to keep the index column.

The following step-by-step example shows how to use this function in practice.

Step 1: Create the Pandas DataFrame

First, let’s create a pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23],
                   'assists': [5, 7, 7, 9, 12, 9],
                   'rebounds': [11, 8, 10, 6, 6, 5]})

#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
5	23	9	5

Step 2: Export the DataFrame to CSV File

Next, let’s export the DataFrame to a CSV file:

#export DataFrame to CSV file
df.to_csv(r'C:UsersBobDesktopmy_data.csv', index=False)

Step 3: View the CSV File

Lastly, we can navigate to the location where we exported the CSV file and view it:

points,assists,rebounds
25,5,11
12,7,8
15,7,10
14,9,6
19,12,6
23,9,5

Notice that the index column is not in the file since we specified index=False.

Also notice that the headers are in the file since the default argument in the to_csv() function is headers=True.

Just for fun, here’s what the CSV file would look like if we had left out the index=False argument:

,points,assists,rebounds
0,25,5,11
1,12,7,8
2,15,7,10
3,14,9,6
4,19,12,6
5,23,9,5

Reference the pandas documentation for an in-depth guide to the to_csv() function.

Additional Resources

How to Read CSV Files with Pandas
How to Read Excel Files with Pandas
How to Export a Pandas DataFrame to Excel
How to Export NumPy Array to CSV File

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