How to Export Dataframe Pandas to CSV file

export-dataframe-pandas-to-csv

Export Dataframe Pandas to CSV : Do you want to save your pandas dataframe in a csv file or another file type? You’ve found the right tutorial! I will explain you how to do it simply in python using different methods to do it. Let’s begin !

Overwiew

Pandas is the most popular data manipulation package in Python. It is often used in data science for processing files and databases. A Pandas dataframe is a type of Pandas data that can store 2D data (rows and columns). When we work on pandas dataframe, it may be necessary in some cases to export the dataframe in a particular format so that we can for example make data visualization on it or simply to share it with other people.

CSV files are a file format often used to export datarames since it is possible to open it easily on excel for example.

Export Pandas DataFrame to a CSV file

To export a pandas dataframe, we have a dataframe! For this we will create a dataframe to illustrate the rest of this tutorial. We will create a dataframe that contains a list of pokemons whose structure is as follows :

Namepokedex_numberprimary_typesecondary_type
Bulbasaur1GrassPoison
Ivysaur2GrassPoison
Venusaur3GrassPoison
Charmander4FireFire
Charmeleon5FireFire
Charizard6FireFlying
Squirtle7WaterWater
Wartortle8WaterWater
Blastoise9WaterWater
Caterpie10BugBug
Pandas Dataframe Pokedex

To create a pandas dataframe with this data, we will need to use the Pandas package. To install it, it is recommended the Pip command, you can use this tutorial to install the version of Pandas you want.

Once you have properly installed Pandas, you will be able to run this code :

import pandas as pd

pokedex = {'Name':['Bulbasaur','Ivysaur','Venusaur','Charmander','Charmeleon','Charizard','Squirtle','Wartortle','Blastoise','Caterpie'],
           'pokedex_number':[1,2,3,4,5,6,7,8,9,10],
           'primary_type' : ['Grass','Grass','Grass','Fire','Fire','Fire','Water','Water','Water','Bug'],
           'secondary_type' : ['Poison','Poison','Poison','Fire','Fire','Flying','Water','Water','Water','Bug']}

df_pokedex = pd.DataFrame(pokedex, columns= ['Name', 'pokedex_number','primary_type','secondary_type'])

print(df_pokedex)
 

Once you have created this dataframe, we will see how to export it in .csv format.

Pandas Dataframe to_csv() function

To export a dataframe, we can use the to_csv() function present in the Pandas module. Its syntax is as follows:

df_pokedex.to_csv(r'C:\Users\Amiradata\Desktop\pokedex.csv')
 

Note : In this example, I used the absolute path to specify the filename. It is also possible to store it in a relative path by specifying only the filename without the tree structure.

There are several options in this function, which are described in detail below:

sep : Specify a custom delimiter for the CSV output, the default is a comma. Its default value is the comma

#sep
df_pokedex.to_csv('pokedex.csv',sep='^') # Use ^ to seperate data
 

float_formatFormat string for floating-point numbers.

#float_format
df_pokedex.to_csv('pokedex.csv',float_format='%.3f') # rounded to three decimals
 

na_rep: Replaces all missing values with the specified string. By default, its value is equal to “”.

#na_rep
df_pokedex.to_csv('pokedex.csv',na_rep='Not specified')
 

index: Specify the row index number. Its value is equal to True by default

#index
df_pokedex.to_csv('pokedex.csv',index=False)
 

header: Export dataframe column names. By default its value is equal to True

#header
df_pokedex.to_csv('pokedex.csv',header=False)
 

columns: The columns to write to the csv file. By default, the value is None, i.e. every column will be exported to the csv file. If a list is specified, only columns in the list will be exported.

#columns
df_pokedex.to_csv('pokedex.csv',columns=['Name'])
 

There are many other options but these are the main and most important ones when exporting a pandas dataframe. You will find the complete list at this address:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

I hope I have brought you new knowledge in the use of the Pandas bookstore. If you want to learn more about dataframes pandas, this book is for you (As an Amazon Partner, I make a profit on qualifying purchases) :

See you soon for a new topic!

By ayed_amira

I'm a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming :)

Leave a comment

Your email address will not be published.