What is DataFrame.to_csv() in pandas?

The DataFrame.to_csv() is a function in pandasa python library that we use to write object to CSVcomma-separated values file.

Syntax


DataFrame.to_csv(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='.', errors='strict', storage_options=None)

Parameters

The function doesn’t have a non-optional parameter.

Below are the commonly used non-optional parameters:

  • path_or_buf: File path or object.

  • sep: It is a string of size 1. The default value is ,.

  • na_rep: Missing data representation. The default value is ,.

  • float_format: It is a format string for floating-point numbers. The default value is None.

  • columns: columns to write.

  • header: It writes out the column names. The default value is True.


To see the list of the rest of the optional parameters, click here.

Return value

The function doesn’t return anything.


If the path_or_buf is None, the DataFrame.to_csv()function returns the resulting CSV format in form of string.

Code

main.py
file_name.csv
import pandas as pd
df = pd.DataFrame({'Name': ['Raphael', 'Donatello'],
'Colors': ['red', 'purple']})
# the dataframe is written to file_name.csv
df.to_csv('file_name.csv')
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources