How To Save a Pandas Data Frame as CSV File?

In this tutorial, we will learn how to save a Pandas Dataframe as CSV or TSV file.

import pandas as pd
pd.__version__

Let us create two lists with some data.

education = ["Bachelor's", "Less than Bachelor's","Master's","PhD","Professional"]
salary = [110000,105000,126000,144200,96000]

We can make a Pandas dataframe using multiple lists. The idea is to create a Python dictionary with variable names as keys and the lists as values. And then use the dictionary as input to Pandas’ DataFrame function to a data frame.

# Create dataframe in one step
df = pd.DataFrame({"Education":education,
                  "Salary":salary})
df
	Education	Salary
0	Bachelor's	110000
1	Less than Bachelor's	105000
2	Master's	126000
3	PhD	144200
4	Professional	95967

How To Write Pandas DataFrame as CSV File?

Now that we have a data frame and ready to save as a file. We will first save the data frame as CSV file, i.e. Comma Separated Value file. We can use Pandas’ to_csv() function to write the dataframe as a CSV file.

# write a pandas dataframe to csv file
df.to_csv("education_salary.csv")

How To Write Pandas DataFrame as CSV File without rowindex?

If you look at the content of the dataframe, it has row index or row names. IN our example, we have 0,1,2, as row index. And you may not want to write the row index to the file.

By specifying the argument “index=False” inside to_csv() function, we can write a dataframe’s content to a CSV file without its row index.

# write a pandas dataframe to csv file without row index
df.to_csv("education_salary.csv", index=False)

How To Write Pandas DataFrame as TSV File?

We can use Pandas’ to_csv() function to write dataframe as Tab Separated Value or TSV file by specifying the argument for separator with sep=”\t”.

# write a dataframe to tsv file
df.to_csv("education_salary.tsv", sep="\t")

How To Write Pandas DataFrame as TSV File without index?

Similarly we can also specify “index=False” inside to_csv() function to save dataframe as TSV file without row index

# write a dataframe to tsv file without index 
df.to_csv("education_salary.tsv", sep="\t", index=False)

This post is part of the series on Pandas 101, a tutorial covering tips and tricks on using Pandas for data munging and analysis.