Sub topic 3
Filtering Rows with Missing Values in pandas
Assume you know basic Python, can create a pandas DataFrame, and have imported pandas as pd. Selection returns rows or columns. Filtering keeps only rows whose condition is true.
Filtering rows with missing values
Missing values are commonly represented by None or NaN. Use isna() to find them and notna() to keep complete values. Do not rely on comparisons such as score == None.
import pandas as pd
scores = pd.DataFrame({
"name": ["x", "y", "z"],
"score": [1.0, None, 3.0],
})
complete = scores[scores["score"].notna()]
missing = scores[scores["score"].isna()]
print(complete)
print(missing)Writing filters with `query`
query() expresses a row filter as a string. It can make several conditions easier to read. Prefix an outside Python variable with @.
minimum = 2
print(scores.query("score >= @minimum"))Column names containing spaces or operators need special handling, so bracket-based masks are often clearer for unusual names.
Filtering columns by name pattern or dtype
Use filter() when column names determine the selection. like searches for text; regex applies a regular expression. Use select_dtypes() when the data type matters.
cities = pd.DataFrame({
"city": ["Oslo", "Lima"],
"population_k": [709, 10092],
"country": ["Norway", "Peru"],
})
print(cities.filter(like="pop"))
print(cities.filter(regex="^c"))
print(cities.select_dtypes(include="number"))Assigning safely and using an index for lookups
Chained indexing, such as df[mask]["column"] = value, may modify a temporary object instead of the original. Select and assign in one .loc operation. Use .copy() when you intentionally need an independent subset.
cities.loc[cities["population_k"] > 5000, "country"] = "Large-country"
large = cities.loc[cities["population_k"] > 5000].copy()
large["label"] = "large"set_index() makes a column the row label, which is useful for key-based lookups.
by_city = cities.set_index("city")
print(by_city.loc["Lima", "population_k"])Fast scalar access with `.at` and `.iat`
Use .at for one value by label and .iat for one value by integer position. Both are suited to scalar access.
print(by_city.at["Lima", "population_k"])
print(by_city.iat[1, 1])Exercise
How should you assign "unknown" to missing values in the country column?
Show answer
Use df.loc[df["country"].isna(), "country"] = "unknown".