0Pricing
Python Academy · Lesson

Indexing, Filtering, and Boolean Masks

Select rows and columns with loc, iloc, and boolean conditions.

loc vs iloc

loc selects by label; iloc selects by integer position. Never mix them up.

import pandas as pd

df = pd.DataFrame({"a":[1,2,3],"b":[4,5,6]}, index=["x","y","z"])
print(df.loc["y"])       # row with label y
print(df.iloc[1])        # row at position 1 (same row)
print(df.loc["x":"y"])   # rows x to y inclusive

Boolean Mask Filtering

Create a boolean Series and use it to select rows. This is the pandas equivalent of NumPy boolean indexing.

import pandas as pd

df = pd.DataFrame({"name":["Alice","Bob","Carol"],"age":[30,17,25]})
adults = df[df["age"] >= 18]
print(adults)
# Alice 30
# Carol 25

All lessons in this course

  1. Series and DataFrame Fundamentals
  2. Indexing, Filtering, and Boolean Masks
  3. GroupBy, Aggregation, and Pivot Tables
  4. Merging, Joining, and Data Cleaning
← Back to Python Academy