By Pankaj Kumar
Pandas DataFrame to_csv() function converts DataFrame into CSV data. We can pass a file object to write the CSV data into a file. Otherwise, the CSV data is returned in the string format.
The syntax of DataFrame to_csv() function is:
def to_csv(
self,
path_or_buf=None,
sep=",",
na_rep="",
float_format=None,
columns=None,
header=True,
index=True,
index_label=None,
mode="w",
encoding=None,
compression="infer",
quoting=None,
quotechar='"',
line_terminator=None,
chunksize=None,
date_format=None,
doublequote=True,
escapechar=None,
decimal=".",
)
Some of the important parameters are:
Let’s look at some common examples of using to_csv() function to convert DataFrame to CSV data.
import pandas as pd
d1 = {'Name': ['Pankaj', 'Meghna'], 'ID': [1, 2], 'Role': ['CEO', 'CTO']}
df = pd.DataFrame(d1)
print('DataFrame:\n', df)
# default CSV
csv_data = df.to_csv()
print('\nCSV String:\n', csv_data)
Output:
DataFrame:
Name ID Role
0 Pankaj 1 CEO
1 Meghna 2 CTO
CSV String:
,Name,ID,Role
0,Pankaj,1,CEO
1,Meghna,2,CTO
csv_data = df.to_csv(sep='|')
print(csv_data)
Output:
|Name|ID|Role
0|Pankaj|1|CEO
1|Meghna|2|CTO
If the specified delimiter length is not 1, TypeError: “delimiter” must be a 1-character string is raised.
csv_data = df.to_csv(columns=['Name', 'ID'])
print(csv_data)
Output:
,Name,ID
0,Pankaj,1
1,Meghna,2
Notice that the index is not considered to be a valid column.
csv_data = df.to_csv(header=False)
print(csv_data)
Output:
0,Pankaj,1,CEO
1,Meghna,2,CTO
csv_data = df.to_csv(header=['NAME', 'ID', 'ROLE'])
print(csv_data)
Output:
,NAME,ID,ROLE
0,Pankaj,1,CEO
1,Meghna,2,CTO
Again the index is not considered as the column of DataFrame object.
csv_data = df.to_csv(index=False)
print(csv_data)
Output:
Name,ID,Role
Pankaj,1,CEO
Meghna,2,CTO
csv_data = df.to_csv(index_label='Sl No.')
print(csv_data)
Output:
Sl No.,Name,ID,Role
0,Pankaj,1,CEO
1,Meghna,2,CTO
with open('csv_data.txt', 'w') as csv_file:
df.to_csv(path_or_buf=csv_file)
We are using with statement to open the file, it takes care of closing the file when the with statement block execution is finished. This code snippet will create a CSV file with the following data.
import pandas as pd
d1 = {'Name': ['Pankaj', 'Meghna'], 'ID': [1, pd.NaT], 'Role': [pd.NaT, 'CTO']}
df = pd.DataFrame(d1)
print('DataFrame:\n', df)
csv_data = df.to_csv()
print('\nCSV String:\n', csv_data)
csv_data = df.to_csv(na_rep="None")
print('CSV String with Null Data Representation:\n', csv_data)
Output:
DataFrame:
Name ID Role
0 Pankaj 1 NaT
1 Meghna NaT CTO
CSV String:
,Name,ID,Role
0,Pankaj,1,
1,Meghna,,CTO
CSV String with Null Data Representation:
,Name,ID,Role
0,Pankaj,1,None
1,Meghna,None,CTO
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
Dear Pankaj, I’m trying to write my data to csv file according to headers. To make it clear, In each column there should ne different values belong to position sensors of a robot. Could you help me to solve this issue? I would be more than happy.
- Kerem
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.