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