Menu
CoddyTech

Filtering Rows

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 38 of 60.

Most questions keep only some rows: flats under 1000 a month, patients over 60. A comparison on a column gives True or False per row, a mask:

The flats table beside its mask, rent under 1000: True for rows 0 and 4, False for the rest; rows 0 and 4 are highlighted as kept, the others fade

flats = pd.DataFrame({
    "area": ["North", "Center", "East", "Center", "West"],
    "rooms": [2, 1, 3, 3, 2],
    "rent": [950, 1200, 1100, 1650, 800],
})
print(flats[flats["rent"] < 1000])

Inside the table's brackets, the mask keeps the True rows, with their labels:

    area  rooms  rent
0  North      2   950
4   West      2   800

Join conditions with & (both) or | (either), each in its own parentheses, as with array masks:

print(flats[(flats["rooms"] >= 2) & (flats["rent"] < 1200)])

This prints:

    area  rooms  rent
0  North      2   950
2   East      3  1100
4   West      2   800

Text works too: flats["area"] == "Center". And .shape[0] counts the rows that matched.

challenge icon

Challenge

Medium

A hiking club lists its trails in trails.csv, with the columns trail, km and climb_m (meters of climbing). The program reads a longest distance max_km and a smallest climb min_climb.

  1. Keep the trails at most max_km long and climbing at least min_climb meters, in picked.
  2. Print picked.
  3. Print how many trails fit, as below.

For a different list of trails:

        trail   km  climb_m
1  Bear Creek  6.0      300
5  Old Quarry  9.2      455
Trails that fit: 2

Try it yourself

import pandas as pd

trails = pd.read_csv("trails.csv")
max_km = float(input())
min_climb = int(input())

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler