Sub topic 2
Selecting Data with `[]`, `loc`, and `iloc`
This chapter assumes basic Python, pandas objects, and table terminology. The key distinction is whether you select by column name, row label, or integer position.
Selecting columns and rows
Square brackets select a column by name. The result is usually a Series, which is a one-dimensional labeled object. Use loc for labels and iloc for integer positions.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
},
index=["a", "b", "c", "d"],
)
print(df["city"]) # one Series
print(df.loc["b", "city"]) # Lima, using labels
print(df.iloc[1, 0]) # Lima, using positions
print(df.loc[["b", "d"], ["city", "pop_m"]])loc includes both endpoints in a label slice. iloc follows normal Python slicing, so its stop position is excluded.
Filtering with boolean masks
A boolean mask is a sequence of True and False values. Use it to keep matching rows. Parentheses are required around each comparison when combining conditions.
large = df.loc[df["pop_m"] > 3, ["city", "pop_m"]]
print(large)Use & for “and” and | for “or”. Do not use Python’s and or or with Series.
Vectorized operations and alignment
A vectorized operation applies to an entire Series without an explicit Python loop.
df["pop_k"] = df["pop_m"] * 1000
print(df["city"].str.upper())Pandas arithmetic aligns Series by their Index labels, not by their visible order.
a = pd.Series([1, 2], index=["x", "y"])
b = pd.Series([10, 20], index=["y", "z"])
print(a + b)The result has x, y, and z. Only y exists in both Series, so it produces 12; the other labels produce NaN, pandas’s marker for a missing numeric value.
Finding and handling missing values
Use isna() to detect missing values, fillna() to replace them, and dropna() to remove them.
values = pd.Series([1.0, None, 3.0])
print(values.isna())
print(values.fillna(values.mean()))
print(values.dropna())Exercise
Which expression selects rows with population above 3 and returns only the city column?
Show answer
df.loc[df["pop_m"] > 3, "city"].