Indexing, Filtering, and Boolean Masks
Select rows and columns with loc, iloc, and boolean conditions.
Indexing, Filtering, and Boolean Masks is a free Python Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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 inclusiveBoolean 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 25Multiple Conditions
Combine boolean conditions with & (and) and | (or). Wrap each condition in parentheses.
import pandas as pd
df = pd.DataFrame({"city":["NY","LA","NY","LA"],"score":[80,90,70,85]})
result = df[(df["city"]=="NY") & (df["score"]>75)]
print(result)query() Method
df.query("expression") accepts a string expression, often more readable than boolean masks.
import pandas as pd
df = pd.DataFrame({"age":[30,17,25],"score":[90,80,70]})
result = df.query("age >= 18 and score > 75")
print(result)isin() Filtering
isin(list) filters rows where a column value is in a given list.
import pandas as pd
df = pd.DataFrame({"city":["NY","LA","Chicago","NY"],"val":[1,2,3,4]})
print(df[df["city"].isin(["NY","LA"])])
# rows with NY or LAbetween() for Range Filtering
series.between(left, right) returns True for values in [left, right] — inclusive by default.
import pandas as pd
df = pd.DataFrame({"score":[55,70,85,95,40]})
print(df[df["score"].between(60, 90)])
# 70 and 85loc for Assignment
Always use loc/iloc for in-place assignment to avoid the SettingWithCopyWarning.
import pandas as pd
df = pd.DataFrame({"val":[1,2,3,4]})
df.loc[df["val"] > 2, "val"] = 99
print(df)
# 0:1 1:2 2:99 3:99at and iat for Single Values
at[label, col] and iat[i, j] provide fast scalar access — faster than loc/iloc for single values.
import pandas as pd
df = pd.DataFrame({"a":[10,20],"b":[30,40]})
print(df.at[0,"a"]) # 10 (by label)
print(df.iat[1,1]) # 40 (by position)Selecting by Dtype
select_dtypes(include/exclude) selects columns by data type.
import pandas as pd
df = pd.DataFrame({"x":[1,2],"name":["a","b"],"score":[1.5,2.5]})
nums = df.select_dtypes(include=["number"])
print(nums.columns.tolist()) # ['x', 'score']Dropping Duplicates
drop_duplicates() removes duplicate rows. Specify subset to compare only certain columns.
import pandas as pd
df = pd.DataFrame({"name":["Alice","Bob","Alice"],"age":[30,25,30]})
print(df.drop_duplicates())
# keeps first Alice, removes secondnlargest and nsmallest
Select the top or bottom N rows by a column value efficiently.
import pandas as pd
df = pd.DataFrame({"product":["A","B","C","D"],"sales":[500,300,800,200]})
print(df.nlargest(2,"sales"))
# C 800
# A 500Quick Check
What is the difference between loc and iloc?
Recap
Use loc[label] for label-based selection and iloc[i] for position-based. Filter rows with boolean masks combined by &/|. Use query() for readable filters, isin() for membership tests, and always assign through loc to avoid SettingWithCopyWarning.
Frequently asked questions
Is the “Indexing, Filtering, and Boolean Masks” lesson free?
Yes — the full text of “Indexing, Filtering, and Boolean Masks” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “Indexing, Filtering, and Boolean Masks”?
Select rows and columns with loc, iloc, and boolean conditions. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Indexing, Filtering, and Boolean Masks” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Series and DataFrame Fundamentals
- Indexing, Filtering, and Boolean Masks
- GroupBy, Aggregation, and Pivot Tables
- Merging, Joining, and Data Cleaning