Skip to content

Informatics Practices · Ch 2 — Data Handling using Pandas – I

Exporting a DataFrame to a CSV file

2.4.2

Exporting a DataFrame to a CSV file

Why Export a DataFrame to CSV?

After you have created, cleaned, or processed a DataFrame in Python, you often need to save it for later use — either to share with others, to open in a spreadsheet like Excel, or to load into another program. The CSV (Comma-Separated Values) format is the most common and portable way to store tabular data. Pandas provides a simple, one-line method to do this: to_csv().

The to_csv() Function

The to_csv() function writes a DataFrame to a text file, typically a CSV file. Its most basic use requires just one argument: the file path where you want the file saved.

Note

The file path must include the folder location and the desired file name, with the extension .csv or .txt.

Example from the textbook:

Suppose you have a DataFrame called ResultDF containing marks of five students in three subjects. To save it, you write:

ResultDF.to_csv(path_or_buf='C:/NCERT/resultout.csv', sep=',')

This creates a file named resultout.csv inside the folder C:/NCERT on your hard disk. When you open that file in a text editor or a spreadsheet, you will see the data exactly as it appeared in the DataFrame — including the row labels (the student names) and the column headers (the subject names) — all separated by commas.

Key Parameters of to_csv()

The function has several useful parameters that let you control exactly what gets written and how.

ParameterPurposeDefault Value
path_or_bufThe file path or a buffer object where the data is writtenRequired (no default)
sepThe delimiter character used to separate values',' (comma)
headerWhether to write the column names (headers) as the first rowTrue
indexWhether to write the row labels (the DataFrame's index) as the first columnTrue

Controlling What Gets Saved

1. Omitting column headers

If you do not want the column names to appear in the output file, set header=False.

2. Omitting row labels

If you do not want the row labels (the index) to be written, set index=False.

3. Using a different separator

You are not limited to commas. You can use any character as a separator by changing the sep parameter. For example, sep='@' will use the @ symbol to separate values.

A Complete Example with Multiple Parameters

The textbook gives this combined example:

ResultDF.to_csv('C:/NCERT/resultonly.txt', sep='@', header=False, index=False)

Here, the file is saved as a .txt file (not .csv), values are separated by @, and neither column headers nor row labels are written. When you open resultonly.txt, you will see only the raw data values, each row separated by @:

90@92@89@81@94
91@81@91@71@95
97@96@88@67@99
``` …
Table 2.11ResultDF
ArnabRamitSamridhiRiyaMallika
Maths9092898194
Science9181917195