What is DataFrame.to_csv() in pandas?

The DataFrame.to_csv() is a function in pandas that we use to write object to CSV 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')

Free Resources