Informatics Practices · Ch 2 — Data Handling using Pandas – I
Exporting a DataFrame to a CSV file
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.
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.
| Parameter | Purpose | Default Value |
|---|---|---|
path_or_buf | The file path or a buffer object where the data is written | Required (no default) |
sep | The delimiter character used to separate values | ',' (comma) |
header | Whether to write the column names (headers) as the first row | True |
index | Whether to write the row labels (the DataFrame's index) as the first column | True |
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
``` …
| Arnab | Ramit | Samridhi | Riya | Mallika | |
|---|---|---|---|---|---|
| Maths | 90 | 92 | 89 | 81 | 94 |
| Science | 91 | 81 | 91 | 71 | 95 |