Sub topic 5
Loading data with read_csv and saving results
This chapter assumes you can build a Series and a DataFrame, and that you know what an Index and a dtype are. Most real work starts by reading a file into a DataFrame and ends by writing a result back out.
What read_csv does
pd.read_csv parses delimited text into a DataFrame. For each column it infers a dtype from the values. It also turns an empty field or a standard missing marker such as NA into NaN. The source can be a file path, a URL, or any file-like object.
Controlling the parse
Inference is convenient but can guess wrong. These parameters give you control:
| Parameter | Purpose |
|---|---|
| `usecols` | Load only the listed columns |
| `index_col` | Use a column as the Index |
| `dtype` | Set the dtype per column |
| `na_values` | Extra strings to treat as missing |
| `parse_dates` | Convert columns to datetimes |
The example uses io.StringIO so it runs without a file on disk. A path works the same way.
import io
import pandas as pd
text = """city,pop_m,region,updated
Oslo,0.7,EU,2024-01-05
Lima,10.7,SA,2024-01-06
Pune,n/a,AS,2024-01-07
Rome,2.8,EU,
"""
df = pd.read_csv(
io.StringIO(text),
index_col="city",
dtype={"region": "category"},
na_values=["n/a"],
parse_dates=["updated"],
)
print(df.dtypes)
print(df.isna().sum())pop_m becomes float64 because n/a is now NaN. Without na_values, that one string would make the whole column object. Rome's empty updated field becomes NaT, the missing marker for datetimes.
Checking what you loaded
Inspect the result before you trust it:
df.head()shows the first rows.df.info()shows dtypes, non-null counts, and memory use.df.shapegives the row and column counts.
A column that you expected to be numeric but shows object usually contains a stray string. Find it, add it to na_values, or clean the column afterwards.
Saving results
DataFrame.to_csv writes the table back out. By default it also writes the Index as the first column.
import pandas as pd
df = pd.DataFrame(
{"pop_m": [0.7, 10.7], "region": ["EU", "SA"]},
index=pd.Index(["Oslo", "Lima"], name="city"),
)
df.to_csv("cities_clean.csv")
back = pd.read_csv("cities_clean.csv", index_col="city")
print(back.equals(df))If the Index is just the default 0, 1, 2 and carries no meaning, pass index=False. Otherwise the next read_csv returns an extra Unnamed: 0 column.
Common errors
- Leading zeros vanish. An ID such as
007is parsed as the integer7. Read it withdtype={"id": str}. - Mixed-type warnings. A column with both numbers and text triggers a
DtypeWarning. Set an explicitdtype. - Wrong delimiter. For semicolon-separated files, pass
sep=";". - Slow loads of wide files. Use
usecolsto read only the columns you need.
Exercise
A CSV has a column zip with values like 02134. After pd.read_csv, the values show as 2134. How do you keep the original text?
Show answer
Pass dtype={"zip": str} to read_csv. Without it, pandas infers an integer type and drops the leading zero.