How to Export Pandas DataFrame to a CSV File
For this excercise, lets create a small Pandas dataframe from scratch. To read data from csv use df.read_csv()
Lets first import the Python Pandas.
import pandas as pd
We will use pd.DataFrame to create the new dataframe.
from pandas import DataFrame
president = {'lastname': ['Obama','Trump','Clinton','Carter'],
'firstyear': [2009,2017,1993,1977]
}
df = DataFrame(president, columns= ['lastname', 'firstyear'])
Lets print our dataframe.
print(df)
We can also use df.head()
df.head()
Pandas DataFrame Write To CSV Using df.to_csv()
Once we have the data in dataframe, we can write to csv file with df.to_csv()
df.to_csv("presidents.csv")
df.to_csv() will save Pandas dataframe to csv in your current directory. Lets check that.
ls -lrt presidents.csv
Yes we got the file written. Lets check the content of this file using unix cat command.
cat presidents.csv
There you go we got our dataframe in to csv file format.
If you do df.to_csv?, you would see lot of options. Lets go through sep option
Lets say we want to use a different delimtter other than comma, use sep option.
df.to_csv("presidents.csv",sep="-")
Lets checkout again
cat presidents.csv | head -2
As we above the csv has "-" as delimtter now.
How to save selected columns of dataframe to csv
Lets say we want to save column lastname of Pandas dataframe to csv file.
df['lastname'].to_csv("presidents.csv")
We got the above warning about the header. Lets cat the file to see what happened.
cat presidents.csv | head -2
We lost the headers. Lets use the option header to False to see if warning goes away.
df['lastname'].to_csv("presidents.csv",header=False)
The warning has gone way. One thing to notice here is that df['lastname'] is series not a dataframe object. Therefore when we use to_csv() on Pandas series, headers are lost.
But how can we get the headers back.
df['lastname'].__class__
Wrap Up!
This post is a primer for users who are new to Python Pandas. I will do second post where I will cover other options of df.to_csv().
Related Topics:
Related Notebooks
- How To Write DataFrame To CSV In R
- How To Append Rows With Concat to a Pandas DataFrame
- Save Pandas DataFrame as CSV file
- How to Convert Python Pandas DataFrame into a List
- How To Iterate Over Rows In A Dataframe In Pandas
- How to Analyze the CSV data in Pandas
- How To Convert Python List To Pandas DataFrame
- How To Read CSV File Using Python PySpark
- How to Sort Pandas DataFrame with Examples