How to Save Pandas Dataframe as csv file

To save Pandas dataframe as CSV file, you can use the function of df.to_csv. The following shows the steps.

df.to_csv(“file_name.csv”)

Step 1: Dataframe example

The following Python code is to generate the sample dataframe.

import pandas as pd
# create a dataframe called df_1
df_1 = pd.DataFrame({'Brand': ['Tesla', 'Toyota','Tesla','Ford'], 
     'Location': ['CA', 'CA','NY','MA']},index=list('abcd'))

# print out the dataframe
print("df_1: \n",df_1)

The following is the print out of the generated sample dataframe.

df_1: 
     Brand Location
a   Tesla       CA
b  Toyota       CA
c   Tesla       NY
d    Ford       MA

Step 2: Save dataframe as CSV file

The following shows Python code to save a dataframe as a CSV file.

# save the pandas dataframe as a csv file
df_1.to_csv("df_1.csv")

Step 3: Remove index (Optional)

You can also remove the index in the csv file by adding index=False.

# save the pandas dataframe as a csv file
df_1.to_csv("df_1.csv",index=False)

Further Reading