Sub topic 9
Selecting Columns and Filtering Rows
This chapter assumes you can load train.csv into a DataFrame called df (see the loading chapter), that you know basic Python lists and dictionaries, and that you have run df.head() and df.info() at least once. Here you learn to pull out the columns and rows you care about, which every later step in the analysis depends on.
Two operations, one idea
Selecting and filtering answer different questions.
- Selecting columns asks "which variables do I want to look at?" You choose by name.
- Filtering rows asks "which passengers do I want to look at?" You choose by a condition, such as "first class" or "age 18 or over".
Both return a new object and leave df unchanged. That matters for exploration: you can cut the data many ways without damaging the original.
Selecting columns
A single column name inside square brackets returns a Series, which is one labeled column of values. A list of names returns a DataFrame, a table with only those columns.
import pandas as pd
df = pd.read_csv("train.csv")
names = df["Name"]
print(type(names))
subset = df[["Name", "Age", "Survived"]]
print(type(subset))
print(subset.head())The double brackets are a common source of confusion. The outer pair is the indexing operation. The inner pair is a Python list of column names. df["Name", "Age"] fails with a KeyError, because pandas treats the comma-separated pair as one tuple key.
You can also write df.Name. Avoid it. It fails for names with spaces, and it collides with existing methods: df.count is a method, not a column called count.
Boolean masks
To filter rows, first build a boolean mask: a Series of True and False values with one entry per row. Then pass the mask to the DataFrame, and pandas keeps the rows where the mask is True.
mask = df["Age"] >= 18
print(mask.head())
print("rows kept:", mask.sum())
adults_only = df[mask]
print(adults_only.shape)mask.sum() works because True counts as 1. This gives a quick way to count matching rows without creating a new table. The mean of a mask gives the share of rows that match.
print((df["Pclass"] == 1).sum())
print((df["Pclass"] == 1).mean())Combining conditions
Combine masks with & (and), | (or), and ~ (not). Wrap every condition in parentheses.
women_first_class = df[(df["Sex"] == "female") & (df["Pclass"] == 1)]
print(len(women_first_class))The parentheses are required because & binds more tightly than ==. Without them, Python tries to evaluate "female" & df["Pclass"] first and raises a TypeError. The Python keywords and, or, and not do not work here either. They ask for the truth value of a whole Series, which is ambiguous, so pandas raises ValueError: The truth value of a Series is ambiguous.
not_first = df[~(df["Pclass"] == 1)]
print(len(not_first))Selecting rows and columns together with loc
df[...] does different things depending on what you pass it: a name selects a column, a mask selects rows. To make intent explicit, use .loc, which takes a row selector and a column selector separated by a comma.
adults = df.loc[df["Age"] >= 18, ["Name", "Age", "Survived"]]
print(adults.head())The first part, df["Age"] >= 18, is a mask for rows. The second part, a list of names, picks columns. Use : to mean "all":
print(df.loc[:, ["Name", "Fare"]].head())
print(df.loc[df["Pclass"] == 3, :].shape).loc selects by label. Slices like df.loc[0:4, "Name":"Age"] include both endpoints, unlike normal Python slices. The default index of a freshly loaded CSV is the integers 0 to n-1, so labels and positions look the same until you filter or sort.
loc versus iloc
.iloc selects by integer position and follows normal Python slicing, where the end is excluded.
print(df.iloc[:5, :3])| Tool | Selects by | Slice end | Accepts boolean mask |
|---|---|---|---|
| `df.loc[rows, cols]` | Labels | Included | Yes |
| `df.iloc[rows, cols]` | Integer positions | Excluded | Only as a plain list or array, not a Series |
For exploration, .loc with masks does most of the work. Use .iloc when you want "the first few rows" or a column by position.
More filters worth knowing
Comparisons are not the only way to build a mask. Several Series methods return masks.
ports = df[df["Embarked"].isin(["C", "Q"])]
mid_fare = df[df["Fare"].between(10, 50)]
no_age = df[df["Age"].isna()]
doctors = df[df["Name"].str.contains("Dr.", regex=False)]
print(len(ports), len(mid_fare), len(no_age), len(doctors))isin(list)replaces a chain of|conditions on one column.between(low, high)includes both ends by default.isna()andnotna()find missing values. Writingdf["Age"] == Noneor== np.nannever matches anything..str.contains(...)works on text columns. Passregex=Falsewhen your pattern has characters like.that regular expressions treat specially. Without it,"Dr."also matches names that contain "Dr" followed by any character.
For text columns with missing values, str.contains returns NaN for those rows, and that breaks filtering. Add na=False to treat them as non-matches.
Missing values and filters
A comparison involving a missing value is False. This has a consequence that is easy to overlook.
older = (df["Age"] >= 18).sum()
younger = (df["Age"] < 18).sum()
unknown = df["Age"].isna().sum()
print(older, younger, unknown, older + younger + unknown, len(df))The three counts add up to the total number of rows. A passenger with no recorded age is in neither Age >= 18 nor Age < 18. If you compute survival for adults and survival for children, those groups silently exclude everyone with a missing age. In the standard train.csv, that is roughly one passenger in five.
Make the exclusion deliberate. Either filter explicitly with df["Age"].notna() and say so in your notes, or keep the missing rows as their own group.
Filtering and then computing
Filtering is often a step toward a number. Once you have a subset, you can summarize it like any other DataFrame.
third_class_men = df.loc[
(df["Pclass"] == 3) & (df["Sex"] == "male"),
["Name", "Age", "Fare", "Survived"],
]
print(third_class_men.shape)
print(third_class_men["Survived"].mean())
print(third_class_men["Fare"].describe())Survived is 0 or 1, so its mean is the survival rate. Report the row count with it. A rate computed from 20 passengers deserves less trust than one from 300.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| `ValueError: The truth value of a Series is ambiguous` | Used `and`, `or`, or `not` | Use `&`, `\ | `, `~` |
| `TypeError` on a comparison with `&` | Missing parentheses around conditions | Wrap each condition in `( )` | |
| `KeyError: ('Name', 'Age')` | Passed names as separate arguments | Pass a list: `df[["Name", "Age"]]` | |
| `KeyError: 'age'` | Column names are case-sensitive | Check `df.columns` | |
| `SettingWithCopyWarning` | Assigned to a filtered slice | Call `.copy()` after filtering | |
| Filter returns fewer rows than expected | Missing values fail every comparison | Count with `isna()` and decide how to treat them |
Modifying a filtered result
If you filter and then add a column, pandas cannot always tell whether you meant to change the original. Take an explicit copy first.
adults = df.loc[df["Age"] >= 18].copy()
adults["IsAdult"] = True
print(adults[["Name", "Age", "IsAdult"]].head())Avoid chained indexing such as df[df["Age"] >= 18]["Age"] = 0. It may assign to a temporary copy and leave df untouched. To change values in place, use a single .loc call: df.loc[mask, "Age"] = 0. During exploration you rarely need this. Create new columns instead of editing the raw ones, which the next chapter covers.
Exercise
Select the Name, Fare, and Embarked columns for passengers who embarked at "S", paid a Fare above 50, and have a known Age. Then count how many rows result and say why df["Age"].notna() is needed only if you want to exclude missing ages on purpose.
Show answer
Use result = df.loc[(df["Embarked"] == "S") & (df["Fare"] > 50) & df["Age"].notna(), ["Name", "Fare", "Embarked"]] and then len(result). The notna() mask is a condition in its own right and needs no comparison, but it does need to be combined with &. It is needed only for deliberate exclusion because a comparison such as df["Age"] >= 18 already drops missing ages silently. Here no comparison involves Age, so without notna() the rows with missing ages would stay in, and the filter would not mention Age at all.
Exercise
Why does df[df["Age"] < 18] plus df[df["Age"] >= 18] fail to cover every row of the Titanic data, and how would you find the passengers left out?
Show answer
A comparison with a missing value evaluates to False, so rows with a missing Age match neither filter. Find them with df[df["Age"].isna()]. The three counts add up to len(df).