pandas Data IO: read_csv, to_csv, JSON, Excel and Parquet
Move data from a file into a DataFrame and back out: read_csv and its everyday options, NaN for empty cells, to_csv with index=False, then JSON, Excel and Parquet, and a read, explore, clean, filter, write pipeline.
What you will learn
- Read a CSV with read_csv and shape the result with sep, index_col, usecols and nrows
- Spot missing values and a missing file right after reading
- Write a CSV with to_csv, and know why index=False avoids the Unnamed: 0 column
- Choose between CSV, JSON, Excel and Parquet, and explain why Parquet suits larger data
Before you start
- pandas Series and DataFrames
- Reading and writing files in Python
Your data doesn't start in a DataFrame. It starts in a file. So getting it in and out is the first job on almost any data task.
Think about a desk and a filing cabinet. The cabinet keeps your papers safe even after you go home, but you can't work on a paper inside the drawer. So you take a copy out to your desk: that's read_csv, a file on disk becoming a DataFrame in memory. You mark it up, and the paper in the drawer doesn't change. But clear the desk and that work is gone: when your program ends, the DataFrame ends with it. So you put a copy back in the cabinet: that's to_csv. Read, process, write.
Reading a CSV file
sales.csv is only text, one line per row, commas between the values:
id,product,price,quantity
1,Notebook,12.5,40
2,Pen,1.2,200
3,Backpack,45.0,15
...
import pandas as pd
df = pd.read_csv("sales.csv")
print(df)
print(df.shape)
id product price quantity
0 1 Notebook 12.50 40
1 2 Pen 1.20 200
2 3 Backpack 45.00 15
3 4 Lamp 23.75 22
4 5 Mug 8.99 60
5 6 Desk 150.00 5
6 7 Stapler 6.40 35
7 8 Folder 3.15 90
(8, 4)
The first line becomes the column names, every other line becomes a row, and pandas adds its own row labels. You didn't split on commas or convert a single number. With Python's csv module you got plain text back (see CSV, JSON and large files in Python); here you get a table with real number columns. The header isn't counted as a row, so the shape is 8 by 4.
Using a column as the index
plain = pd.read_csv("sales.csv")
indexed = pd.read_csv("sales.csv", index_col="id")
print(plain.columns.tolist())
print(indexed.columns.tolist())
print(indexed.loc[3, "product"])
['id', 'product', 'price', 'quantity']
['product', 'price', 'quantity']
Backpack
The file already has its own labels in id. With index_col="id", that column becomes the row labels, and you can find a row by its id with .loc (more on that in loc, iloc and filtering). If your file has an id column, say so, or it stays just another column.
The options you'll use most
df = pd.read_csv(
"sales.csv",
sep=",",
index_col="id",
usecols=["id", "product", "price"],
nrows=5,
)
print(df)
print(df.columns.tolist())
product price
id
1 Notebook 12.50
2 Pen 1.20
3 Backpack 45.00
4 Lamp 23.75
5 Mug 8.99
['product', 'price']
sepis the character between values. Comma is the default; you need it when a file uses something else.usecolspicks the columns to load, soquantitynever gets read. Keepidin the list, because it's the index.nrowsreads only the first rows, handy for a quick look at a big file.
Gaps in a file, and a file that isn't there
In sales_gaps.csv, Pen has no price and row 3 has no product:
df = pd.read_csv("sales_gaps.csv")
print(df)
print(df["price"].dtype)
print(df.isna().sum())
id product price
0 1 Notebook 12.50
1 2 Pen NaN
2 3 NaN 45.00
3 4 Lamp 23.75
float64
id 0
product 1
price 1
dtype: int64
read_csv doesn't complain. Each empty cell becomes NaN, and price is still a float column. Check for gaps right after you read; fixing them is covered in data cleaning and wrangling.
try:
df = pd.read_csv("sales_oct.csv")
except FileNotFoundError as error:
print("Not found:", error)
Not found: [Errno 2] No such file or directory: 'sales_oct.csv'
Check the spelling first, then the folder you're running from: a plain file name is looked up in the current folder.
Writing a CSV file
df = pd.read_csv("sales.csv")
df["total"] = df["price"] * df["quantity"]
df.to_csv("output.csv", index=False)
print(open("output.csv").read())
id,product,price,quantity,total
1,Notebook,12.5,40,500.0
2,Pen,1.2,200,240.0
3,Backpack,45.0,15,675.0
4,Lamp,23.75,22,522.5
5,Mug,8.99,60,539.4
6,Desk,150.0,5,750.0
7,Stapler,6.4,35,224.0
8,Folder,3.15,90,283.5
output.csv is a new file with the total column in it. sales.csv hasn't changed.
Why index=False
df = pd.read_csv("sales.csv", nrows=3)
df.to_csv("with_index.csv")
back = pd.read_csv("with_index.csv")
print(open("with_index.csv").read())
print(back.columns.tolist())
,id,product,price,quantity
0,1,Notebook,12.5,40
1,2,Pen,1.2,200
2,3,Backpack,45.0,15
['Unnamed: 0', 'id', 'product', 'price', 'quantity']
Without it, the row labels are written as an extra column with no name (the header starts with a comma). Read the file back and pandas calls it Unnamed: 0, a column nobody asked for. You'll find it in a lot of files. Unless your row labels mean something, write index=False.
Options for writing
df = pd.read_csv("sales.csv", nrows=3)
df = df[["product", "price"]]
df.to_csv(
"prices.csv",
index=False,
sep=";",
float_format="%.2f",
)
print(open("prices.csv").read())
print(pd.read_csv("prices.csv", sep=";"))
product;price
Notebook;12.50
Pen;1.20
Backpack;45.00
product price
0 Notebook 12.5
1 Pen 1.2
2 Backpack 45.0
Semicolons for the tools that expect them, and two decimals in the file. To read it back you must pass sep=";" too. The format changed the text in the file, not the number.
JSON, Excel and Parquet
pandas keeps one pattern for every format: read_something brings data in, to_something sends it out.
df = pd.read_csv("sales.csv", nrows=2)
df = df[["product", "price"]]
df.to_json("api_data.json")
print(open("api_data.json").read())
df.to_json("records.json", orient="records")
print(open("records.json").read())
print(pd.read_json("api_data.json"))
{"product":{"0":"Notebook","1":"Pen"},"price":{"0":12.5,"1":1.2}}
[{"product":"Notebook","price":12.5},{"product":"Pen","price":1.2}]
product price
0 Notebook 12.5
1 Pen 1.2
By default JSON is grouped by column. orient="records" gives one object per row, the shape you'll often see from web APIs.
Excel needs a helper package, openpyxl, listed in the project's requirements.txt:
df = pd.read_csv("sales.csv")
df.to_excel("report.xlsx", index=False)
back = pd.read_excel("report.xlsx")
print(back.head(3))
print(back.shape)
id product price quantity
0 1 Notebook 12.5 40
1 2 Pen 1.2 200
2 3 Backpack 45.0 15
(8, 4)
read_excel reads the first sheet by default. When your data comes from people who work in spreadsheets, this is your route.
Parquet keeps your types
Parquet is a format built for data work. It needs pyarrow.
df = pd.DataFrame({
"code": ["007", "010", "042"],
"price": [12.5, 1.2, 45.0],
})
df.to_csv("codes.csv", index=False)
df.to_parquet("codes.parquet")
print(pd.read_csv("codes.csv")["code"].tolist())
back = pd.read_parquet("codes.parquet")
print(back["code"].tolist())
print(back["price"].dtype)
[7, 10, 42]
['007', '010', '042']
float64
A CSV is only text, so 007 looks like a number when it's read back, and the leading zeros are gone. Parquet stores each column's type with the data, so the codes come back as text. It's a binary format you can't read in a text editor, but pandas opens it in one line.
Why Parquet suits larger data
import os
import pandas as pd
n = 100_000
df = pd.DataFrame({
"id": range(n),
"product": ["Pen", "Mug", "Lamp", "Desk"] * (n // 4),
"price": [10 + (i % 97) * 0.75 for i in range(n)],
"quantity": [i % 50 + 1 for i in range(n)],
})
df.to_csv("big.csv", index=False)
df.to_parquet("big.parquet")
print("csv bytes:", os.path.getsize("big.csv"))
print("parquet bytes:", os.path.getsize("big.parquet"))
few = pd.read_parquet("big.parquet", columns=["price"])
print(few.shape)
csv bytes: 1970402
parquet bytes: 623321
(100000, 1)
A CSV writes one row after another. Parquet keeps each column together, like one folder for prices and another for products, and similar values side by side compress well: here it's roughly a third of the size. And with columns=["price"] it loads just that one column, while a CSV reader still has to go through every line.
Which format, when
| Format | Use it for | Read / write |
|---|---|---|
| CSV | Plain text almost any tool opens; the safe choice for sharing | read_csv / to_csv |
| JSON | Web services and APIs | read_json / to_json |
| Excel | People who work in spreadsheets | read_excel / to_excel |
| Parquet | Larger data, and keeping column types | read_parquet / to_parquet |
Read, explore, clean, filter, write
This is the shape of most data work. sales_raw.csv has a messy header with capitals and spaces: ID, Product , Price.
import pandas as pd
# 1. Read
df = pd.read_csv("sales_raw.csv")
# 2. Explore
df.info()
# 3. Clean column names
df.columns = df.columns.str.strip().str.lower()
# 4. Filter
df = df[df["price"] > 10]
# 5. Write
df.to_csv("sales_clean.csv", index=False)
print(open("sales_clean.csv").read())
<class 'pandas.DataFrame'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 ID 8 non-null int64
1 Product 8 non-null str
2 Price 8 non-null float64
dtypes: float64(1), int64(1), str(1)
memory usage: 367.0 bytes
id,product,price
1,Notebook,12.5
3,Backpack,45.0
4,Lamp,23.75
6,Desk,150.0
info() shows the spaces around Product and Price. strip and lower fix the names so you can simply write df["price"]. The filter drops eight rows to four, and a clean file lands on disk.
Recap
read_csvbrings a file into a DataFrame;sep,index_col,usecolsandnrowsshape what you get.- Empty cells become
NaN; check withisna().sum()right after reading. to_csv(..., index=False)keeps theUnnamed: 0column out.- JSON, Excel and Parquet follow the same read/to pattern. Parquet keeps types and is smaller.
Try it yourself: read sales.csv, keep the rows with a quantity over 30, and save them to Parquet. Or ask an AI tool to write it, then read every line it gives you.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
