How to export Pandas DataFrame to a CSV file in Python

In this tutorial, we will learn how to export a pandas Dataframe to a CSV file in Python using a simple example.

Pandas is a powerful data science library in Python used for data manipulation and analysis by data analysts all around the world. It provides labelled data structures called dataframes which are very useful to clean and analyze data stored in csv or excel files.

First, let us install pandas.

pip install pandas

Now, that we have installed pandas in our IDE, let us import it.

import pandas as pd

Here, we want to export a DataFrame to a csv file of our choice. So, we will need a dataframe first. We can easily create a dataframe in Python using dictionaries and lists.

student = ['Ramesh', 'Suresh', 'Mahesh']
Marks = ['90', '80', '60']
Rank = ['First', 'Second', 'Third']

dict = {'Student':student, 'Marks':Marks, 'Rank':Rank}

Now, that we have the data, we convert this into a DataFrame using pd.Dataframe() function. We store the dataframe in a variable df.

df = pd.DataFrame(dict)
print(df)

Output:

  Student Marks    Rank
0  Ramesh    90   First
1  Suresh    80  Second
2  Mahesh    60   Third

Here, we have the DataFrame ready. Now, we have to export it to a csv file of our choice. To do that, we use another built-in pandas function called pd.to_csv(). Also, to be able to find our new CSV file easily, we should specify the path to the directory where the CSV file is to be stored.

df.to_csv(r'C:\Users\Downloads\Record.csv')

As a result, the CSV file has been stored in the downloads folder. You should be able to find it easily. So we have successfully able to export Pandas Dataframe to a CSV file using Python.

Leave a Reply

Your email address will not be published. Required fields are marked *