Show contents
Chapter 2 of 7 · 20 min
Filter, sort and fill the gaps
By the end of this chapter, you'll be able to
- Filter rows with boolean masks and combine them
- Sort a DataFrame by one or several columns
- Select rows and columns with loc
- Find and handle missing values
Filter with a mask
A comparison on a column does not return a single boolean, but a Series of booleans, one per row: this is a mask. Placed in square brackets, it keeps only the rows where it is True.
import io
import pandas as pd
csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\ngroundnut,Thiès,60,640\n"
sales = pd.read_csv(io.StringIO(csv))
mask = sales["kg"] > 100
print(mask.tolist())
print(sales[mask])
[True, False, False, True, True, False]
product region kg price_kg
0 millet Kaolack 120 300
3 millet Thiès 200 300
4 mango Ziguinchor 150 250
Masks are combined with & (and), | (or) and ~ (not). Each condition must be in parentheses:
import io
import pandas as pd
csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\ngroundnut,Thiès,60,640\n"
sales = pd.read_csv(io.StringIO(csv))
print(sales[(sales["region"] == "Thiès") & (sales["kg"] >= 50)])
print(sales[sales["product"].isin(["millet", "cowpea"])])
product region kg price_kg
3 millet Thiès 200 300
5 groundnut Thiès 60 640
product region kg price_kg
0 millet Kaolack 120 300
2 cowpea Thiès 45 500
3 millet Thiès 200 300
isin tests membership of a list: it is easier to read than a chain of |.
Placed in square brackets, the mask keeps only the rows where it is True.
Text description of the animation
- We start from a whole column.
- The comparison applies to every value at once.
- The result is a Series of booleans, aligned with the rows.
- Placed in square brackets, the mask keeps only the rows where it is True.
Sort
sort_values sorts by one column, or several in order of priority. ascending=False reverses the order:
import io
import pandas as pd
csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\ngroundnut,Thiès,60,640\n"
sales = pd.read_csv(io.StringIO(csv))
print(sales.sort_values("kg", ascending=False).head(3))
print(sales.sort_values(["region", "kg"], ascending=[True, False]))
product region kg price_kg
3 millet Thiès 200 300
4 mango Ziguinchor 150 250
0 millet Kaolack 120 300
product region kg price_kg
0 millet Kaolack 120 300
1 groundnut Kaolack 80 650
3 millet Thiès 200 300
5 groundnut Thiès 60 640
2 cowpea Thiès 45 500
4 mango Ziguinchor 150 250
Sorting keeps each row's original index: you can see where each sale comes from. reset_index(drop=True) renumbers from 0 if needed.
Select with loc
loc[rows, columns] selects both rows (by mask or by index label) and columns (by name). It is also the right way to change chosen values:
import io
import pandas as pd
csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,Kaolack,80,650\ncowpea,Thiès,45,500\nmillet,Thiès,200,300\nmango,Ziguinchor,150,250\ngroundnut,Thiès,60,640\n"
sales = pd.read_csv(io.StringIO(csv))
print(sales.loc[sales["region"] == "Kaolack", ["product", "kg"]])
sales.loc[sales["product"] == "millet", "price_kg"] = 320
print(sales["price_kg"].tolist())
product kg
0 millet 120
1 groundnut 80
[320, 650, 500, 320, 250, 640]
Missing values
Real data has gaps. pandas represents them as NaN (Not a Number). Calculation functions ignore them, but you need to know where they are and decide what to do with them:
import io
import pandas as pd
csv = "product,region,kg,price_kg\nmillet,Kaolack,120,300\ngroundnut,,80,650\ncowpea,Thiès,,500\nmillet,Thiès,200,\n"
sales = pd.read_csv(io.StringIO(csv))
print(sales)
print(sales.isna().sum())
print(sales["kg"].mean())
print(sales.dropna())
print(sales.fillna({"region": "unknown"}))
product region kg price_kg
0 millet Kaolack 120.0 300.0
1 groundnut NaN 80.0 650.0
2 cowpea Thiès NaN 500.0
3 millet Thiès 200.0 NaN
product 0
region 1
kg 1
price_kg 1
dtype: int64
133.33333333333334
product region kg price_kg
0 millet Kaolack 120.0 300.0
product region kg price_kg
0 millet Kaolack 120.0 300.0
1 groundnut unknown 80.0 650.0
2 cowpea Thiès NaN 500.0
3 millet Thiès 200.0 NaN
isna().sum()counts the gaps per column:Truecounts as 1 in a sum;mean()averages the present values only;dropna()removes incomplete rows,fillna()replaces gaps with a value.
Note: the kg column has switched to decimals (float64), because NaN is a special decimal number.
Mini-lab: the sales under the microscopePython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: sales to check
The manager wants the list of incomplete or suspicious sales: those where the weight is missing, or where the weight is over 500 kg (probably a typo). Display these rows, sorted by product, with only the product and kg columns.
csv = "product,region,kg\nmillet,Kaolack,120\ngroundnut,Kaolack,\ncowpea,Thiès,45\nmillet,Thiès,2000\nmango,Ziguinchor,150\n"
Hint 1
sales["kg"].isna() is a mask, just like sales["kg"] > 500.Hint 2
|, then use loc to choose the columns and sort_values to sort.Show the solution and common mistakes
import io
import pandas as pd
csv = "product,region,kg\nmillet,Kaolack,120\ngroundnut,Kaolack,\ncowpea,Thiès,45\nmillet,Thiès,2000\nmango,Ziguinchor,150\n"
sales = pd.read_csv(io.StringIO(csv))
to_check = sales["kg"].isna() | (sales["kg"] > 500)
print(sales.loc[to_check, ["product", "kg"]].sort_values("product"))
product kg
1 groundnut NaN
3 millet 2000.0
Common mistakes:
- Testing
sales["kg"] == Noneor== float("nan"):NaNis equal to nothing, not even itself. Always useisna(). - Removing incomplete rows with
dropna()before looking for anomalies: you would remove precisely the rows to check.
Summary
- 1A comparison on a column produces a boolean mask; sales[mask] keeps the rows where it is True.
- 2Masks are combined with &, | and ~, each condition in parentheses; isin tests a list of values.
- 3sort_values sorts by one or several columns, in ascending or descending order.
- 4loc[rows, columns] selects and changes chosen values.
- 5Missing values (NaN) are found with isna, removed with dropna or replaced with fillna.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.