Sub topic 3
Loading the Titanic CSV
This chapter assumes you can run Python in a notebook or script, have pandas installed, and know what a function call and a dictionary are. You should also have train.csv, the Titanic training file, in your working directory. Here you load the file and check that the load worked. The next chapter inspects the contents in more detail.
What read_csv does
A CSV (comma-separated values) file is plain text. Each line is a row, and commas separate the fields. pd.read_csv parses that text into a DataFrame, which is pandas' table type. It reads the first line as column names and guesses a dtype (data type) for each column from the values it finds.
import pandas as pd
df = pd.read_csv("train.csv")
print(type(df))
print(df.shape)df.shape is a tuple of (rows, columns). For the Kaggle training file it is (891, 12). A different shape means you loaded a different file, such as the test file, which lacks Survived, or a modified copy.
The steps of a load
Checking the load
Do not assume the load worked. Run three checks right away.
print(df.shape)
print(df.head())
df.info()head()shows the first five rows. Check that the values sit under the right column names.info()lists each column's dtype and its non-null count. It prints directly, so do not wrap it inprint.- A column with the wrong dtype is a warning sign. If
Ageappeared asobject, some value in it would not be a number.
In this dataset, Survived, Pclass, SibSp, and Parch load as integers. Age and Fare load as floats. Name, Sex, Ticket, Cabin, and Embarked load as object, which is how pandas stores text. Age is a float even though ages look like whole numbers. Missing values are stored as NaN (not a number), a float marker, and an integer column cannot hold NaN.
Common loading errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `FileNotFoundError` | The working directory is not where the file is | Check `os.getcwd()` or use a full path |
| One wide column with commas inside | The file uses another separator, such as `;` or a tab | Pass `sep=";"` or `sep="\t"` |
| `ParserError` | A row has more fields than the header | Inspect the file, and avoid `on_bad_lines="skip"` until you know what you would drop |
| Numbers loaded as `object` | Stray text such as `"N/A"` or `"?"` in the column | Pass `na_values=["N/A", "?"]` |
Check your working directory like this:
import os
print(os.getcwd())
print(os.path.exists("train.csv"))Useful read_csv options
You do not need most options for Titanic, but these come up often:
usecols=["Survived", "Pclass", "Sex", "Age"]loads only the columns you name, which saves memory on wide files.index_col="PassengerId"uses a column as the row label instead of the default 0, 1, 2, and so on.dtype={"Pclass": "category"}sets a dtype yourself instead of letting pandas guess.nrows=100reads only the first 100 rows, which is handy for a quick test on a large file.
small = pd.read_csv(
"train.csv",
usecols=["Survived", "Pclass", "Sex", "Age", "Fare"],
nrows=100,
)
print(small.shape)Keep the full df as your working table. Later chapters assume all twelve columns are present.
Exercise
You load a CSV and info() shows that Fare has dtype object, although you expected numbers. What is the most likely cause, and how can you handle it at load time?
Show answer
At least one value in the column is not a number, such as "?" or "N/A", so pandas falls back to text for the whole column. Pass those markers to na_values in read_csv, for example na_values=["?", "N/A"], so they become NaN and the column loads as float.