Sub topic 3
Loading the Titanic CSV
This chapter covers how to read the Titanic training file into a DataFrame and confirm that it loaded correctly. It assumes you can run Python code in a notebook or script, have pandas installed, and know what a DataFrame is from the previous chapter. The file is train.csv, the Titanic training set from the Kaggle "Titanic: Machine Learning from Disaster" competition. It has 891 passenger rows and 12 columns. Put it in the folder you run your code from, or use the path-handling approach below.
What a CSV file is
A CSV (comma-separated values) file is plain text. Each line is a row, and commas separate the fields. The first line usually holds the column names. The format stores no types, so 29, 1 and male are all just characters until the reader decides how to interpret them. Most loading problems come from that gap between text and types.
The first lines of train.csv look like this:
PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,SThe name field is wrapped in double quotes because it contains a comma. The empty field between 7.25, and ,S is a missing Cabin. read_csv handles both cases for you.
The basic call
pd.read_csv takes a path and returns a DataFrame:
import pandas as pd
df = pd.read_csv("train.csv")
print(df.shape)
print(df.head())
df.info()The default behavior is to treat the first line as column names, split on commas, and infer a dtype for each column. It also converts empty fields and a few other strings to NaN, pandas' marker for a missing value.
Where the file is
A relative path like "train.csv" is resolved against the current working directory. That is the folder the process started in, which is not always the folder holding your script or notebook. When you see FileNotFoundError, check the working directory first:
from pathlib import Path
print(Path.cwd())
path = Path("data") / "train.csv"
if not path.exists():
raise FileNotFoundError(f"Expected the Titanic file at {path.resolve()}")
df = pd.read_csv(path)read_csv accepts Path objects as well as strings. Building paths with Path avoids hard-coded separators, so the same code runs on Windows, macOS and Linux. The path argument can also be an http(s) URL or a file-like object. For a learning project, a local copy is better because the analysis then still works offline and the data cannot change underneath you.
The load, step by step
The diagram shows what happens inside the call and which choices you control.
For clean files such as this one, the defaults are enough. The options matter when a file is large, messy or ambiguous.
Options worth knowing
The table lists the parameters you will use most often.
| Parameter | What it does | Example |
|---|---|---|
| `usecols` | Reads only the listed columns, which saves memory | `usecols=["Survived", "Sex", "Age"]` |
| `dtype` | Forces a type per column instead of inferring | `dtype={"Sex": "category"}` |
| `index_col` | Uses a column as the row index | `index_col="PassengerId"` |
| `nrows` | Reads only the first N data rows | `nrows=100` |
| `na_values` | Extra strings to treat as missing | `na_values=["?", "unknown"]` |
| `sep` | Field separator for non-comma files | `sep=";"` |
| `encoding` | Text encoding of the file | `encoding="latin-1"` |
Here is an example that combines several of them on a small slice:
import pandas as pd
small = pd.read_csv(
"train.csv",
usecols=["PassengerId", "Survived", "Pclass", "Sex", "Age", "Fare", "Embarked"],
index_col="PassengerId",
dtype={"Sex": "category", "Embarked": "category"},
nrows=100,
)
print(small.dtypes)
print(small.index.is_unique)nrows is a good way to test a loading recipe quickly before you commit to the full file. It is also a trap. Statistics computed on the first 100 rows describe those rows, not the dataset, and they can differ a lot if the file is sorted. Remove nrows before you start analysing.
Keep the main DataFrame simple
For this tutorial, load the full file with defaults into df. Later chapters group by Pclass and call df.corr(numeric_only=True). If you converted Pclass to a categorical type, it would drop out of the correlation matrix. Convert types in a copy or a derived column, and leave the loaded data as it came.
Index choice
PassengerId runs from 1 to 891 and is unique, so it works as an index. The default RangeIndex (0 to 890) is also fine, and it is what the chapter examples and later chapters assume. If you set index_col="PassengerId", df.loc[1] selects the passenger with ID 1, whereas with the default index df.loc[1] selects the second row. Pick one and stay consistent.
What dtype inference does
pandas reads each column and picks the narrowest type that fits all its values. In this file:
Survived,Pclass,SibSpandParchbecome integers (int64).AgeandFarebecome floats (float64).Ageis a float partly because it contains missing values, and plainint64cannot holdNaN.Name,Sex,Ticket,CabinandEmbarkedbecomeobject, the general dtype for text.
One bad value can change a whole column. If a single row in a numeric column contained "?", the column would load as object and arithmetic on it would fail. When a column you expect to be numeric shows up as object, look for stray strings and either pass them in na_values or convert with pd.to_numeric(df["col"], errors="coerce").
Integer-looking codes can mislead too. Pclass is stored as the integers 1, 2 and 3, but they are class labels, not quantities. The average of class 1 and class 3 is not a meaningful "class 2". Keep that in mind when you reach correlations.
Missing value markers
By default, read_csv treats these strings as missing: an empty field, NA, N/A, NaN, nan, null, NULL, n/a and a few others. This is useful but occasionally wrong. In a dataset of country codes, NA is Namibia, and the default would turn it into a missing value. You can switch that off with keep_default_na=False and then list the markers you want with na_values. Titanic does not have this problem, but check the raw text when a column's missing count looks suspicious.
Verify the load
Do not assume that a load that raised no error is correct. Add a few cheap checks right after it:
import pandas as pd
df = pd.read_csv("train.csv")
expected_columns = [
"PassengerId", "Survived", "Pclass", "Name", "Sex", "Age",
"SibSp", "Parch", "Ticket", "Fare", "Cabin", "Embarked",
]
assert list(df.columns) == expected_columns, "Unexpected columns"
assert df.shape == (891, 12), f"Unexpected shape: {df.shape}"
assert df["PassengerId"].is_unique, "PassengerId should be unique"
print("Load looks correct:", df.shape)These assertions document what you expect of the file. If you later download a different version, they fail immediately instead of letting a mismatch spread through the analysis. Keep this block at the top of your notebook.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `FileNotFoundError` | Wrong working directory or filename | Print `Path.cwd()`, then use an absolute path or move the file |
| `UnicodeDecodeError` | File is not UTF-8 | Try `encoding="latin-1"` or the encoding the source documents |
| `ParserError: Error tokenizing data` | Wrong separator or malformed rows | Inspect the raw text, set `sep`, or investigate the bad line |
| One column, with commas inside every value | File uses another separator such as `;` or tab | Set `sep=";"` or `sep="\t"` |
| An `Unnamed: 0` column | The file was saved with its index as a column | Use `index_col=0` or drop the column |
| A numeric column has dtype `object` | Stray strings such as `"?"` | Use `na_values` or `pd.to_numeric(..., errors="coerce")` |
Summary of the routine
- Confirm the working directory and file path.
- Call
pd.read_csvwith defaults first. - Check shape, column names and key uniqueness with assertions.
- Only add
usecols,dtype,na_valuesorencodingwhen the defaults give a wrong result, and note why.
The next chapter looks at the loaded table more closely with head, info and dtypes.
Exercise
You load the file with pd.read_csv("train.csv", nrows=100) and report that the mean Age is the average for Titanic passengers. What is wrong with this, and what single change fixes it?
Show answer
nrows=100 reads only the first 100 data rows, so the mean describes those rows, not all 891 passengers, and they may not be representative if the file has any ordering. Remove nrows (use it only for quick tests) so the full file is loaded before computing statistics.
Exercise
After loading, df["Fare"].dtype is object instead of float64. Name two likely causes and one way to repair the column.
Show answer
Likely causes are stray non-numeric strings in the column (for example "?" or "unknown") or a currency symbol or thousands separator in the values. Repair it by passing the strings in na_values when calling read_csv, or by converting after loading with pd.to_numeric(df["Fare"], errors="coerce"), which turns unparseable values into NaN.