Sub topic 9
Selecting columns and filtering rows
This chapter assumes you can run Python in a notebook or script, know basic pandas objects (Series and DataFrame), and have loaded train.csv into a DataFrame named df. Selecting and filtering let you look at one slice of the data at a time. That is the step before comparing groups.
Selecting columns
A single column in brackets returns a Series. A list of column names in double brackets returns a DataFrame.
import pandas as pd
df = pd.read_csv("train.csv")
ages = df["Age"]
print(type(ages))
subset = df[["Name", "Age", "Survived"]]
print(type(subset))
print(subset.head())Use the single-bracket form when you want one column to compute with. Use the list form when you want to view or pass along several columns.
Filtering rows with boolean masks
A comparison such as df["Sex"] == "female" produces a Series of True and False values, one per row. This is a boolean mask. Putting the mask inside df[...] keeps only the rows where it is True.
To combine conditions, use & for "and", | for "or", and ~ for "not". Wrap each condition in parentheses, because & binds more tightly than == or >=.
women_first_class = df[(df["Sex"] == "female") & (df["Pclass"] == 1)]
print(len(women_first_class))
adults = df.loc[df["Age"] >= 18, ["Name", "Age", "Survived"]]
print(adults.head())Choosing rows and columns together with loc
df.loc[row_selector, column_selector] picks rows and columns in one step. The row selector can be a boolean mask, and the column selector can be a list of names. In the second example above, loc keeps only passengers aged 18 or older and returns three columns.
loc is also the safe way to assign to a filtered selection. Writing df[mask]["Age"] = 0 may change only a temporary copy, and pandas often warns about this. Writing df.loc[mask, "Age"] = 0 changes df itself. During exploration you will rarely need to assign, so prefer to leave the raw columns alone.
Missing values inside filters
A comparison with a missing value is never True. The filter df["Age"] >= 18 therefore drops every row where Age is missing, and so does df["Age"] < 18. The two groups do not add up to the whole table. Check this directly.
adults = (df["Age"] >= 18).sum()
minors = (df["Age"] < 18).sum()
unknown = df["Age"].isna().sum()
print(adults, minors, unknown, len(df))The first three numbers sum to the fourth. If you want the rows with unknown age, use df["Age"].isna() explicitly.
Common errors
| Symptom | Likely cause | Fix | Column |
|---|---|---|---|
| `KeyError: 'age'` | Column names are case-sensitive | Check `df.columns` and use `"Age"` | |
| "truth value of a Series is ambiguous" | Used `and` or `or` | Use `&` or ` | ` with parentheses |
| Filter result is smaller than expected | Missing values were dropped by the comparison | Count `isna()` separately | |
| `SettingWithCopyWarning` | Assigned to a filtered copy | Use `df.loc[mask, "col"] = value` |
Exercise
Write code that selects the Name and Fare columns for passengers who embarked at "S" and paid more than 50. Why must each condition be in parentheses?
Show answer
df.loc[(df["Embarked"] == "S") & (df["Fare"] > 50), ["Name", "Fare"]]. The & operator binds more tightly than == and >, so without parentheses pandas would try to evaluate expressions like "S" & df["Fare"] first and raise an error.
Exercise
A colleague says that filtering Age < 18 and Age >= 18 together covers every passenger. Is that correct? How would you check?
Show answer
No. Rows with a missing Age fail both comparisons. Check with df["Age"].isna().sum() and confirm that the counts of the two filters plus the missing count equal len(df).