How to Export Pandas DataFrame to the CSV File

How to Export Pandas DataFrame to the CSV File
How to Export Pandas DataFrame to the CSV File

Export Pandas DataFrame to the CSV File

In this tutorial, you are going to learn how to Export Pandas DataFrame to the CSV File in Python programming language. Here in this tutorial, we will do the following things to understand exporting pandas DataFrame to CSV file:

  1. Create a new DataFrame.
  2. Export the DataFrame to CSV File.

Basic Structure

df.to_csv(r’PATH_TO_STORE_EXPORTED_CSV_FILE\FILE_NAME.csv’)

1. Create new DataFrame

We are going to export the following data to CSV File:

NameAgeScore
John2089
Sara2178
Jack2194
Ricky2056

Now let’s write the Python program for that:

First, we will import the pandas module and then we will create DataFrame.

NOTE: If you have not installed pandas package install it by using pip tutorial.

The following program simply creates a DataFrame and prints values:

The output should be:

How to Export Pandas DataFrame to the CSV File - Simple Program Output
How to Export Pandas DataFrame to the CSV File – Simple Program Output

2. Export the DataFrame to CSV File

As given in the above program we have successfully created a DataFrame. Now to export the DataFrame to CSV file we are going to use the following function:

export_csv = df.to_csv(r’C:\Users\CrazyGeeks\Desktop\dataframe.csv’, index = None, header=True)

Where,

So the complete program should look like:

The output file exported to desktop (C:\Users\CrazyGeeks\Desktop\dataframe.csv):

How to Export Pandas DataFrame to the CSV File - output file
How to Export Pandas DataFrame to the CSV File – output file

The exported CSV file looks like:

How to Export Pandas DataFrame to the CSV File - excel output
How to Export Pandas DataFrame to the CSV File – excel output

3. Another Example

If you don’t want to specify the specific location then you can just enter the name of the file. The exported file will be stored in the current directory where the program is located.

Conclusion

You have successfully learned How to Export Pandas DataFrame to the CSV File. If you have any queries please don’t forget to comment out.

LEAVE A REPLY

Please enter your comment!
Please enter your name here