LambdaLab
Informatics Practices · Class 12 · Python Pandas · DataFrame
PandasDataFrame⏱️ 8 min read

CSV Files

Data doesn't usually live in your code — it lives in files. The most common is the CSV (Comma-Separated Values): plain text where each line is a row and commas separate the fields.

1What a CSV looks like

A CSV is just text. The first line is usually the header (the column names); every line after is one row of data:

Students.csv
Name,English Marks,IP Marks,Maths Marks
Ritu,77,83,69
Pankaj,72,95,87
Ajay,81,99,94

Pandas offers two functions: read_csv() to load a CSV into a DataFrame, and to_csv() to write a DataFrame back out.

2Reading a CSV

Note
On your own computer you'd pass a file path, e.g. pd.read_csv("Students.csv"). Hover over the 📄 Students.csv pill on the console header to view the virtual file contents stored in the browser.
read_csv.py
📄 Students.csv

Notice two things: the first line became the column names, and the rows got an automatic index starting at 0.

3Writing a CSV

to_csv() turns a DataFrame back into CSV text. On a real computer you pass a filename (df.to_csv("Marks.csv")) to save it on your disk.

Run the playground below! Once executed, a flashing green 💾 Marks.csv badge will appear next to the filename on the console header. Hover over it to view the CSV content generated by your Python code!

to_csv.py
Key Takeaway
pd.read_csv("file.csv") loads a CSV into a DataFrame (first line → column names, rows indexed from 0). df.to_csv("file.csv") writes it back out.
Quick Check

When you read a CSV, what happens to its first line by default?

Quick Check

How do you write a DataFrame to CSV without the row index?