A model cannot read a spreadsheet. It reads arrays of numbers. Between the spreadsheet and the array there is a lot of ordinary work: open the file, see what is in it, find the empty cells, fix the typos, keep the rows you want, count things by group, and turn words into numbers. That work is called data wrangling, and it takes up a large share of the time in real projects. The tool for it in Python is pandas.
This lesson teaches pandas through one data set that every machine learning course uses: the passengers of the ship Titanic. For each of 1309 passengers the file says which class they travelled in, their sex, their age, what they paid, and whether they survived. We will load it, look at it, ask questions of it, clean it, and end with the arrays X (the inputs) and y (the answer) that a model such as logistic regression (P3.A7) would train on.
Pandas is not a plotting tool (P2.4 teaches that) and not a modelling tool (P3 does). It builds on NumPy (P2.2): you will see arrays underneath all the time.
A table is a dictionary of columns
Pandas has two main objects.
A Series is one column: a list of values with a label for each value. The labels are called the index.
A DataFrame is a table: several Series that share the same index, one per column, each with a name.
Here is a tiny made-up example. Run it: the first run downloads Python and pandas (about 14 MB, shown on the cell), and your browser keeps them afterwards.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
Ann 22 Bo 38 Cy 26 Name: age, dtype: int64 Bo is 38 and the first value is 22 [23 39 27]
Three things to notice.
- The Series has an index (
Ann,Bo,Cy) and a dtype, the type of every value in it (int64: whole numbers). Arithmetic such asages + 1is applied to every value at once. There is no loop. This is the same vectorization as in NumPy (P2.2). ages["Bo"]finds a value by its label.ages.iloc[0]finds it by its position. The difference matters a lot, and we come back to it.ages.to_numpy()gives the plain NumPy array. A Series is, for numbers, an array with labels attached.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
name age survived 0 Ann 22 0 1 Bo 38 1 2 Cy 26 1 name str age int64 survived int64 dtype: object (3, 3) ['name', 'age', 'survived'] [22 38 26]
A DataFrame has an index (the row labels, here 0, 1, 2 by default), columns (the names), and one dtype per column. A single column is a Series: tiny["age"]. Writing tiny[["name", "age"]], with a list inside the brackets, gives a smaller DataFrame.
| Part | In the example | How to see it |
|---|---|---|
| Index (row labels) | 0, 1, 2 | df.index |
| Columns (names) | name, age, survived | df.columns |
| dtype of each column | str, int64, int64 | df.dtypes |
| Shape (rows, columns) | (3, 3) | df.shape |
| The values as a NumPy array | [[...], ...] | df.to_numpy() |
The common dtypes are int64 (whole numbers), float64 (decimals; also what a whole-number column becomes when it has missing values, since NaN is a float), bool, str (text), category (a few repeated labels), and datetime64 (dates and times). This lesson’s cells run pandas 3, which shows text columns as str (pandas 2 shows object).
The data: Titanic passengers
The file is titanic3.csv from the Vanderbilt University Department of Biostatistics (Frank Harrell’s data repository). It has 1309 rows, one per passenger, and 14 columns. We keep the file exactly as published, and we credit it below. A CSV file (“comma-separated values”) is plain text with one row per line and the values separated by commas.
| Column | Meaning |
|---|---|
pclass | Ticket class: 1, 2 or 3 (a rough stand-in for wealth) |
survived | The answer we would predict: 1 survived, 0 did not |
name | Name, with a title such as Mr. or Miss. |
sex | male or female |
age | Age in years (babies have fractions); some are missing |
sibsp | Number of siblings or spouses aboard |
parch | Number of parents or children aboard |
ticket, fare | Ticket number; fare paid in British pounds |
cabin, embarked | Cabin; port of boarding (C Cherbourg, Q Queenstown, S Southampton) |
boat, body | Lifeboat number (if the person left in a boat); number of a recovered body |
home.dest | Home town and destination |
The data were collected by researchers from passenger lists (mainly the Encyclopedia Titanica), so they contain gaps and some errors. Treat the file as a data set to practise on, not as a precise historical record.
The cells below run in your browser. Each cell is complete by itself (it loads the file again), so you can run any of them in any order, and you can edit the code. They show the result of the last line, like a notebook, and tables are printed at most 56 characters wide so that they fit a phone. The grey output you see before running was computed in advance with pandas 3.0.2, the same version the browser runs.
The walk-through
Step 1: load the file
pd.read_csv reads a CSV file into a DataFrame. Then ask for its shape, the number of rows and columns, and look at the first rows with head(). (import pandas as pd is the standard short name.)
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
(1309, 14) pclass survived sex age 0 1 1 female 29.00 1 1 1 male 0.92 2 1 0 female 2.00 3 1 0 male 30.00 4 1 0 female 25.00
The index on the left, 0, 1, 2, ..., was made by pandas. The data are sorted by class and then by name, so head() shows only first-class passengers. Never judge a file by its first rows alone: df.sample(5) shows random rows, and tail() shows the last ones.
Step 2: a first look
Before any question, ask four things: what columns are there and what types, how many values are present, how are the numbers spread, and how often does each category occur? This is the habit of descriptive statistics (P1.D12), done with pandas.
df.info() lists every column with its count of non-missing values and its dtype.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
<class 'pandas.DataFrame'> RangeIndex: 1309 entries, 0 to 1308 Data columns (total 14 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 pclass 1309 non-null int64 1 survived 1309 non-null int64 2 name 1309 non-null str 3 sex 1309 non-null str 4 age 1046 non-null float64 5 sibsp 1309 non-null int64 6 parch 1309 non-null int64 7 ticket 1309 non-null str 8 fare 1308 non-null float64 9 cabin 295 non-null str 10 embarked 1307 non-null str 11 boat 486 non-null str 12 body 121 non-null float64 13 home.dest 745 non-null str dtypes: float64(3), int64(4), str(7)
Read it carefully. age has 1046 values out of 1309, so some are missing. cabin has only 295. body has 121. A column with so few values needs a decision, not a blind average.
value_counts() counts the values of a column. describe() gives the count, mean, standard deviation, minimum, quartiles and maximum of the numeric columns (the quartiles and the median are explained in P1.D12).
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
survived
0 809
1 500
Name: count, dtype: int64
survival rate: 0.382
sex
male 843
female 466
Name: count, dtype: int64
pclass
1 323
2 277
3 709
Name: count, dtype: int64
age fare
count 1046.00 1308.00
mean 29.88 33.30
std 14.41 51.76
min 0.17 0.00
25% 21.00 7.90
50% 28.00 14.45
75% 39.00 31.28
max 80.00 512.33What we learn: 500 of 1309 passengers survived, a rate of 0.382, so the two answers are not equally common (this is mild class imbalance, P3.A10). There are 843 men and 466 women, and 709 passengers in third class against 323 in first and 277 in second. The median age is 28, and fares are very skewed: the median fare is 14.45 pounds, but the maximum is 512.33. A mean would be pulled up by that tail (P1.D12).
Step 3: missing values
A missing value is stored as NaN (“not a number”). isna() gives True where a value is missing, and .sum() counts the True values (True counts as 1). A column of True and False made by isna() is called a mask.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
pclass 0 survived 0 name 0 sex 0 age 263 sibsp 0 parch 0 ticket 0 fare 1 cabin 1014 embarked 2 boat 823 body 1188 home.dest 564 dtype: int64 share of ages missing: 0.201
263 of 1309 ages (20.1%) are missing, and 1014 cabins. fare is missing once and embarked twice. The first question is why. A cabin number is missing mostly because most passengers had no recorded cabin. An age may be missing because nobody wrote it down. Which of the two it is changes what you should do. We come back to what to do after we can select rows.
Statistics skip NaN by default: df["age"].mean() averages the 1046 known ages. That is convenient, and it can hide a problem, which is why we count the missing values first.
Step 4: pick rows and columns
There are three ways to select, and each has one job.
df["age"]picks a column (a Series).df[["age", "fare"]]picks several (a DataFrame)..loc[rows, columns]picks by label. A slice of labels includes both ends:df.loc[0:2]gives the rows labelled 0, 1 and 2..iloc[rows, columns]picks by position, counted from 0 like a Python list. A slice excludes the end:df.iloc[0:2]gives rows 0 and 1.
With the default index the label and the position of a row are equal until you sort or filter, and then they are not. That is why the two exist.
To keep rows that satisfy a condition, put a boolean mask inside the brackets: df[df["sex"] == "female"]. Join conditions with & (and), | (or) and ~ (not), and wrap every condition in parentheses.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
pclass sex age survived 0 1 female 29.00 1 1 1 male 0.92 1 2 1 female 2.00 0 pclass sex 0 1 female 1 1 male 144 first-class women; survival rate 0.965
144 first-class women are in the file, and 96.5% of them survived. This one number already says a lot: sex and class matter, and a model should be given both.
Now the classic bug. In Python, & binds more tightly than ==, so df["sex"] == "female" & df["pclass"] == 1 is read as df["sex"] == ("female" & df["pclass"]) == 1, which makes no sense. Writing and fails for a different reason: and needs one single True or False, but a Series holds a whole column of them.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
TypeError ValueError works, selects 144 rows
The first two lines raise an error (TypeError and ValueError; the exact message depends on the pandas version). Only the version with parentheses and & works.
df.query("pclass == 1 and age > 60") is a shorter way to write a filter: the condition is a string, and inside it and and or are allowed. It is nice for simple cases. Use masks when a condition gets complicated or uses variables from your program (then write @name inside the query).
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
21 rows 0.286
Changing values, and the copy trap
To change values, use one .loc call with the rows and the column: df.loc[mask, "age"] = 0.
The tempting alternative is chained assignment: df[mask]["age"] = 0. That is two steps: first df[mask] makes a new object, then ["age"] = 0 writes into it. Whether the original table changes depended in old pandas on whether the first step returned a copy or a view, which is hard to predict. Pandas 2 warned with SettingWithCopyWarning, and sometimes the assignment worked and sometimes not.
Pandas 3 made this simple: with copy-on-write, every selection behaves as a copy of the data, so a chained assignment never changes the original. Instead of the old warning, pandas 3 gives a warning called ChainedAssignmentError, to tell you the write went nowhere. (Copy-on-write was available as an option in pandas 2.x, and is the default and only mode from pandas 3.0.)
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
warning: ['ChainedAssignmentError'] zeros after chained assignment: 0 zeros after .loc: 323
In the run above the chained assignment left 0 zeros: it wrote into a temporary copy. The single .loc call set all 323 first-class ages. If you read older code or tutorials, be ready to see .copy() calls that silence the old warning; in pandas 3 they are not needed to avoid it, but a .copy() is still the clear way to say “I want an independent table”.
Step 5: groups
The most useful question about a table is “how does this number differ between groups?”. groupby answers it in three steps: split the rows into groups, apply a function (mean, count, …) to each group, and combine the results into a table.
The survival column holds 1 and 0, so its mean is the share of survivors: a proportion (P1.D12). Group by sex, then by class and sex.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
sex
female 0.727
male 0.191
Name: survived, dtype: float64
mean count
pclass sex
1 female 0.965 144
male 0.341 179
2 female 0.887 106
male 0.146 171
3 female 0.491 216
male 0.152 493
pclass 1 2 3
sex
female 0.97 0.89 0.49
male 0.34 0.15 0.15This is the main finding of the walk-through. Women survived at 72.7% and men at 19.1%. Within each class, women did much better than men. And class mattered a lot for women (96.5%, 88.7% and 49.1%) but much less for men (34.1%, 14.6% and 15.2%). The last table is a pivot_table: the same groups laid out as a grid, with one grouping variable down the side and one across the top. A pivot table is a groupby that has been reshaped to read like a spreadsheet.
Two warnings. A rate for a group is only as trustworthy as the number of rows behind it (count): 106 second-class women is plenty, but a group of 5 would give a very shaky rate (the margin of error is the subject of P1.D13). And these are associations in one data set. They describe who survived. They do not by themselves explain why.
Step 6: clean the data and build X and y
Now we prepare the data for a model. Four checks first. Each takes one line.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
duplicate rows: 0
sex values: ['female', 'male']
embarked values: {'S': 914, 'C': 270, 'Q': 123, nan: 2}
fare of 0: 17 fare max: 512.3292
age range: 0.17 to 80.0
mean size
boat
False 0.028 823
True 0.981 486There are no duplicate rows. sex has exactly two values, with no typos. embarked has two missing values. There are 17 fares of 0 (a free ticket, an unrecorded fare or a mistake: the file does not say, so we keep them and remember it). The ages run from 0.17 (about two months) to 80, so they are plausible. The fare maximum of 512.33 is a real outlier, but several passengers share it, so it is probably real and not a typo.
The last line is the important one. Passengers with a value in boat (a lifeboat number) survived 98.1% of the time. Passengers with none survived 2.8%. The boat column is a leak: it is filled in almost only for people who survived, because it records the lifeboat they left in. It is a consequence of the outcome, not a cause or a clue known beforehand. A model that sees it would look brilliant on this file and would be useless in a situation where you want to predict survival before the event. The body column leaks too, in the opposite direction: it is filled in only for people who died (all 121 passengers with a body number did not survive). We must leave both out of X. Spotting a leaking column is one of the most valuable things a first look can do (P3.A11).
New columns
A new column is a vectorized formula on existing columns, assigned to a new name. Three tools cover most needs:
- Arithmetic on columns:
df["fare"] / df["pclass"], or(df["sex"] == "female").astype(int)for a 0/1 column. .map(dictionary): replaces each value using a lookup table. Values not in the dictionary becomeNaN.np.where(condition, a, b): picksawhere the condition is true andbelsewhere.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
group adult 1155 child 154 Name: count, dtype: int64 rows with missing age: 263 is_female sex_code group 0 1 1 adult 1 0 0 child 2 1 1 child
Look at the counts: 1155 adults and 154 children. But the file has 263 missing ages. A comparison with NaN is always false (NaN < 18 is False), so np.where quietly called every passenger with an unknown age an adult. The code worked and produced a plausible-looking column that is wrong for 263 rows. Handle missing values before you build features from them, or build the column so that missing stays missing.
Go deeper The last resort: apply, row by row
There is a last resort for anything the methods above cannot do: df.apply(function, axis=1) calls your Python function once per row. It works for everything, and it is usually much slower than the vectorized forms because the loop runs in Python and not in compiled code. Try to write the formula on whole columns first.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
True True 11 {1: 790, 2: 235, 3: 159}Missing values: your options
There are four common choices, and none is always right.
- Drop the rows with
df.dropna(subset=["age"]). Simple, but here it throws away 20% of the passengers, and they are not a random 20% (208 of the 263 are in third class), so the remaining data may not represent everyone. - Drop the column with
df.drop(columns=["cabin"]). Reasonable forcabin(77% missing). - Fill with a typical value using
fillna. For a numeric column the median is a common choice, since it is not dragged by outliers (P1.D12). A mean also works. For a category, the most common value. - Fill and flag. Fill the number and add a 0/1 column
age_missing, so a model can learn that “missing” itself carries information.
Whichever you use, there is one rule about when to compute the fill value. A model is judged on rows it has not seen (P3.A4). If you compute the median age from all rows, including the test rows, information about the test set has leaked into your training. This is a small leak in this case, but it is the same mistake as the big ones. Compute the fill value from the training rows only and apply that same number to the test rows.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
median age, train rows: 28.25 median age, test rows: 27.0 (never use this) missing left: 0
The training median is 28.25, and the test rows alone would give 27.0. We used 28.25 for both and never looked at the test rows’ own ages. (sample(frac=0.8, random_state=2) picks 80% of the rows at random and, because of the seed, the same ones every time. The correct way to split is the subject of P3.A4.)
Categories, dummies and sorting
A model needs numbers, so text columns must be converted. Two simple encodings:
- Codes:
astype("category")stores each label once and the rows as small integer codes. This saves memory and is what many tools expect, but integer codes suggest an order that may not exist. - One-hot encoding:
pd.get_dummies(column)makes one 0/1 column per category, so “S, C, Q” becomes three columns, exactly one of which is 1 in each row. Since pandas 2 the default columns areTrue/False, so passdtype=intfor numbers. (The encodings are discussed in P3.A11.)
sort_values(col, ascending=False) sorts rows by a column. Note that the index labels travel with the rows: the sorted frame has labels such as 49, 50, 183, not 0, 1, 2. That is why .loc and .iloc can then disagree.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
category ['female', 'male'] [0, 1, 0]
emb_C emb_Q emb_S
0 0 0 1
1 0 0 1
2 0 0 1
pclass fare
49 1 512.3292
50 1 512.3292
183 1 512.3292The final step: X and y
Now we put it together: choose the columns that are known before the outcome, turn each into numbers, fill the gaps, and convert to NumPy. y is the answer. X is the features.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
0 missing values left
(1309, 7) float32 (1309,)
0 1 2
pclass 1.0000 1.00 1.00
is_female 1.0000 0.00 1.00
age 29.0000 0.92 2.00
age_missing 0.0000 0.00 0.00
fare 211.3375 151.55 151.55
sibsp 0.0000 1.00 1.00
parch 0.0000 2.00 2.00We have a feature matrix of shape (1309, 7) and a target vector of shape (1309,): 1309 passengers, 7 numbers each. Nothing is missing. We left out boat and body because they leak, and we left out name, ticket, cabin and home.dest because they would need more work to turn into useful numbers (that is feature engineering, in P3.A11). We used float32 because that is the usual type for neural networks. These arrays go straight into a model, or into PyTorch:
import torch # not available in the browser cells, but in Colab (P2.6)
X_t = torch.from_numpy(X_np) # a tensor sharing memory with the NumPy array
y_t = torch.from_numpy(y).float() # the 0/1 target as floats
Other tools you will need
Several statistics at once
.agg takes a list of functions, or named results, in one call. size counts the rows of a group, and count counts the non-missing values in a column. They differ exactly when there are missing values.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
rows ages_known rate median_age pclass 1 323 284 0.62 39.0 2 277 261 0.43 29.0 3 709 501 0.26 24.0
In first class there are 323 passengers but only 284 known ages, so size is 323 and count is 284. The median age falls with class: 39, 29 and 24. Never read a statistic without checking how many values it is based on.
Joining two tables
Real data live in several tables: one for customers, one for orders. merge joins rows that have the same value in a key column, like a database join. how="left" keeps every row of the left table and fills NaN where there is no match. how="inner" keeps only rows that match in both.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
pclass embarked port 0 1 S Southampton 1 1 NaN NaN 2 2 S Southampton 3 3 S Southampton pclass embarked port 0 1 S Southampton 1 2 S Southampton 2 3 S Southampton
Row 168 has no port (NaN), so it has no match. The left join keeps it with NaN, and the inner join drops it. Always check the row count before and after a merge. If the key is not unique in the right table, a merge multiplies rows, a quiet and common bug.
Dates [deeper]
Go deeper Dates and times
A column of date strings is just text until you convert it with pd.to_datetime. Then the .dt accessor gives the parts (.dt.year, .dt.month, .dt.day_name()), and subtracting two dates gives a time difference. Models usually need such parts as features (month, weekday), since a raw date string means nothing to them. (The two dates here are made up.)
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
['Wednesday', 'Tuesday'] [1, 3] 34 days apart
Time zones and mixed formats are the usual troubles. Parse with an explicit format= when you know it, so that 03/04/2024 is not read as March 4 in one row and April 3 in another.
A cleaning checklist
Real tables are messier than Titanic. Before modelling, go through this list. Each item is one or two lines of pandas.
- Duplicate rows. Find:
df.duplicated().sum(). Fix:df.drop_duplicates(). - Typos and case in categories. Find:
df[col].value_counts(). Fix:.str.strip().str.lower(), or.replace({"M": "male"}). - Numbers stored as text. Find:
df.dtypes,info(). Fix:pd.to_numeric(col, errors="coerce")(bad values becomeNaN). - Missing values. Find:
df.isna().sum(). Fix: drop, fill or flag (see above). - Impossible values. Find:
df.describe(),df[col].between(lo, hi). Fix: decide whether to correct, set toNaN, or drop. - Outliers. Find: quartiles and the 1.5 IQR rule (P1.D12). Fix: keep them if they are real; cap or drop them if they are errors, and say what you did.
- Mixed units. Find: compare ranges between sources. Fix: convert to one unit in a new column.
- Leaking columns. Find: ask “would I know this at prediction time?” Fix: drop them.
A tiny messy table shows three of these at once. The three cities are the same city, one price is not a number, and after cleaning two rows are identical.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
city price
0 paris 10.0
1 paris 12.0
2 paris NaN
3 rome 7.0
4 rome 7.0
duplicates: 1
city price
0 paris 10.0
1 paris 12.0
2 paris NaN
3 rome 7.0After .str.strip().str.lower() the three versions of Paris became one value. to_numeric(..., errors="coerce") turned abc into NaN (the column is now float64, which is why 10 shows as 10.0). Only then did duplicated() find the repeated Rome row. The order matters: clean first, then look for duplicates.
Go deeper Common bugs and interview questions
Bugs not met above
- Forgetting that
fillnareturns a new Series:df["age"].fillna(0)alone does nothing todf. Assign the result. (inplace=Trueis rarely needed and best avoided.) - A merge that duplicates rows because the key repeats in the right table.
get_dummiescolumns that differ between training and test data because a category is missing in one of them.
(The and/& bug, loc versus iloc, the NaN comparison trap, chained assignment and filling before splitting are taught above and in the exercises.)
Questions you may be asked
- What is the difference between
.locand.iloc? Labels versus positions.locslices include the end label,ilocslices exclude the end position. - Why
&and notand?andasks for one truth value, while&works element by element; and&binds tighter than==, so each comparison needs parentheses. - What do
sizeandcountdo in agroupby?sizecounts rows.countcounts non-missing values in a column. - How would you handle missing values? Count them, find out why, then drop, fill (median or most common) or flag. Fit the fill value on the training data only.
- How do you get from a DataFrame to a model? Choose numeric columns, handle missing values, encode categories, then
.to_numpy()forXandy.
Where this shows up in machine learning
Every supervised project in Part 3 starts as this lesson ends: a table, a target column, a feature matrix. Fill values and encodings are fitted on the training rows only (P3.A4, P3.A11). A PyTorch Dataset (P2.7) often wraps the arrays that .to_numpy() produced. And the first look, with its counts and missing-value report, is how you catch class imbalance, typos and leaks before a model quietly learns from them.
Intuition
Think of a DataFrame as a spreadsheet that you drive with code. Instead of clicking a cell, you name a column. Instead of copying a formula down, you write it once for the whole column. Instead of a pivot-table wizard, you write groupby. The index is the row number you can keep or change, and the dtype is the “format” of the column, which you cannot mix within one column.
Where the analogy breaks: a spreadsheet lets any cell hold anything. A DataFrame column has one dtype, and a number column with a single bad text entry becomes text, and arithmetic on it fails.
Math
A group mean of a 0/1 column is a conditional proportion. If is the survival of passenger and is a group (say first-class women), then the number groupby(...).mean() computes is
For = first-class women, and the sum is , so the estimate is . It is an estimate from a sample (P1.D10), and the fewer rows in , the less it can be trusted. Filling with the median replaces each missing by , so the filled column has the same median and a smaller spread than the real values would have. A feature matrix is with rows and columns, and the target is (P3.A1).
Code
The whole walk-through, compressed into one cell. It uses mostly the lines you have seen, plus a small function so that the training and test rows are treated in exactly the same way.
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
(1047, 7) (262, 7) survival rate, train: 0.386 test: 0.366
Try it: explore on your own
Change the code, add lines and run. A few questions to try: Which port had the highest survival rate? Is the median fare of third-class men different from that of third-class women? What happens to the survival rate if you drop the rows with a missing age?
Runs real pandas in your browser. First run downloads about 14 MB (Python 6, NumPy 3, pandas 5; once) and a 117 KB data file.
pclass sex
1 female 80.92915
male 49.50420
2 female 23.00000
male 13.00000
3 female 10.48960
male 7.89580
Name: fare, dtype: float64Common mistakes
Check your understanding
You want the first-class women in the Titanic frame. Which line works?
The version with parentheses around each comparison and an ampersand between them builds two masks and combines them element by element. Without parentheses the ampersand is evaluated before the comparisons (it binds tighter), which gives an error. The version with the word and fails because and needs one single True or False and a Series holds many. A comma inside the brackets is not read as two conditions: pandas treats it as one odd key and raises an error as well.
A frame has the default index 0, 1, 2, 3, 4. How many rows do
df.loc[0:2]anddf.iloc[0:2]return?A label slice with loc includes its end, so labels 0, 1 and 2 give three rows. A position slice with iloc, like a Python list slice, stops before its end, so positions 0 and 1 give two rows. The options that give equal counts ignore this difference, and the option with two rows for loc and three for iloc has the two rules swapped.
In the Titanic data 263 ages are missing. After
d["group"] = np.where(d["age"] < 18, "child", "adult"), what group do those passengers get?Any comparison with NaN is False, so the condition is false for these rows and np.where picks the second value, adult. No error is raised and no NaN is kept, which is why the result looks fine and is wrong. NaN is not smaller than numbers; it is not ordered with them at all.
For the first-class passengers,
sizeis 323 andcountofageis 284. What does that tell you?Size counts rows, and count counts only the non-missing values in the chosen column, so the difference 323 minus 284 is the number of missing ages. The count of ages says nothing about adults or survival, and duplicates would show up in the number of rows, not in a missing-value difference.
You will fill missing ages with the median before training a model. Which value is correct?
The fill value is learned from data, so it may only be learned from the training rows, and the same number is then applied to the test rows. A median from the whole file lets information about the test rows leak into training, and a median computed from the test rows treats the two sets differently and uses test labels or features to set up the model. Zero is not a real age in this file (the youngest is 0.17) and would pull the ages down and distort the model.
df.groupby("sex")["survived"].mean()gives 0.191 for men. What does that number mean?The survived column holds 1 and 0, so its mean within the group of men is the share of men who survived, 161 of 843. The share of survivors that were men is a different ratio (161 of 500, about 32%). A difference between groups is not given by one group mean, and the number describes this file only, not shipwrecks in general.
Exercises
Use the cells above (edit them) to compute these. The answers were computed with the same file.
- How many passengers are under 18 (known ages only), how many of them survived, and what is their survival rate?
Show answer
kids = df[df["age"] < 18]. There are 154 of them, 81 survived, so the rate is 0.526 (len(kids),kids["survived"].sum(),kids["survived"].mean()). Passengers with a missing age are not in this count, because the comparison withNaNis false. - Find the survival rate and the number of passengers for each port of boarding.
Show answer
df.groupby("embarked")["survived"].agg(["mean", "size"])gives C: 0.556 (270), Q: 0.358 (123), S: 0.333 (914). The two passengers with no port are left out, sincegroupbydrops missing keys by default. (Do not conclude that the port itself mattered: Cherbourg passengers were more often in first class, which is a confounder, P1.D13.) - What is the mean fare paid by third-class men?
Show answer
df[(df["pclass"] == 3) & (df["sex"] == "male")]["fare"].mean()is 12.42 pounds. The parentheses around each condition are required. - Add a column
family = sibsp + parch + 1and compare the survival rate of people travelling alone (family == 1) with the others.Show answer
df["family"] = df["sibsp"] + df["parch"] + 1, thendf.groupby(df["family"] == 1)["survived"].agg(["mean", "size"]). Alone: 0.303 over 790 passengers. Not alone: 0.503 over 519. - One passenger has no fare. Find the row, and choose a fill value that is better than the overall median.
Show answer
df[df["fare"].isna()]shows a third-class man, age 60.5, boarded at S (row 1225). Fares depend strongly on class, so the median fare of third class, 8.05, is a better guess than the overall median, 14.45. With a train/test split you would compute that median from the training rows only. - The line
df[df["age"] > 60]["survived"] = 0does not changedf. Explain why and write a working version.Show answer
The first brackets make a new object (a copy, in pandas 3), and the second assignment writes into that temporary object. Writedf.loc[df["age"] > 60, "survived"] = 0to change the original in one step. (The data would then be wrong; the example only shows the syntax.) pd.get_dummies(df["pclass"], prefix="pclass", dtype=int)gives three columns. Why might you passdrop_first=True, and how many columns result?Show answer
Withdrop_first=Trueyou get 2 columns. The three one-hot columns always add up to 1, so any one of them can be computed from the other two. For a linear model with an intercept this redundancy makes the weights non-unique (the columns are perfectly collinear). Tree models do not mind. The dropped class is the “reference”.- Each name has a title between a comma and a dot, such as
Mr. Extract it withdf["name"].str.extract(r", ([A-Za-z ]+)\.")and count the most common titles.Show answer
titles = df["name"].str.extract(r", ([A-Za-z ]+)\.")[0]and thentitles.value_counts().head(). The top ones are Mr 757, Miss 260, Mrs 197, Master 61, then Dr 8 and Rev 8. No name is left without a title (0 missing). The title mixes sex and age (Master is a boy) and is a standard example of feature engineering (P3.A11).
Credits
The data are titanic3 from the Vanderbilt University Department of Biostatistics (data repository of Frank E. Harrell Jr., hbiostat.org/data), which grants permission to anyone wishing to use the data sets. The file was updated by Thomas Cason (University of Virginia) from the Encyclopedia Titanica, and one of the original sources was the passenger list in Eaton and Haas (1994). It reflects the data available as of 2 August 1999. Data obtained from http://hbiostat.org/data courtesy of the Vanderbilt University Department of Biostatistics. We did not change a single value. The copy of the file on this site is titanic.csv, 1309 rows and 14 columns (117 KB).