Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
csv
python
dataframe
communitycreator

What is DataFrame.to_csv() in pandas?

Hammad Nasir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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')

RELATED TAGS

pandas
csv
python
dataframe
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring