How to Export Pandas DataFrame to CSV (With Example)

Exporting data from Pandas to CSV is an easy process. To do this, simply use the DataFrame.to_csv() method and provide the file name as the argument. This will create a file with the given name and save it in the same directory as the script. The data in the DataFrame can also be modified before it is exported, such as by adding a header to the CSV file or changing the index. Example: df.to_csv(‘example.csv’)


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

How to Export NumPy Array to CSV File

x