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.


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.

     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

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

Further Reading