Use Boolean indexing to filter rows of a DataFrame
Expt. No.12
Page No.24
Boolean indexing
Aim
To write a Python program that uses Boolean indexing to display the rows of a DataFrame that meet one or more conditions.
Concepts used
Algorithm
- Create a DataFrame of students.
- Display rows where Marks > 80.
- Display rows where Marks > 60 and Class is "XII", combining conditions with & and brackets.
- Display only the names of students with marks below 70 using loc with a condition.
Program
# Boolean indexing on a DataFrame import pandas as pd df = pd.DataFrame({"Name": ["Asha", "Rohan", "Ira", "Kabir", "Diya"], "Class": ["XII", "XII", "XI", "XI", "XII"], "Marks": [82, 67, 88, 91, 59]})print("Marks above 80:")print(df[df["Marks"] > 80])print("Class XII with marks above 60:")print(df[(df["Marks"] > 60) & (df["Class"] == "XII")])print("Names of students below 70:")print(df.loc[df["Marks"] < 70, "Name"])
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python dataframe_boolean_indexing.py
Marks above 80:
Name Class Marks
0 Asha XII 82
2 Ira XI 88
3 Kabir XI 91
Class XII with marks above 60:
Name Class Marks
0 Asha XII 82
1 Rohan XII 67
Names of students below 70:
1 Rohan
4 Diya
Name: Name, dtype: object
✓ Printed by running this program, not typed by hand.
Result
Three students scored above 80, two Class XII students scored above 60 (Asha and Rohan), and Rohan and Diya were listed as scoring below 70.
Viva voce: what the examiner may ask
01What is Boolean indexing?
Selecting rows with a Series of True/False values; only rows with True are kept.
02Why are & and brackets used instead of and?
and works on single values; & works element by element on Series, and brackets are needed because & has higher precedence than >.
03How do you write "or" between two conditions?
With |, e.g. (df["Marks"] > 90) | (df["Class"] == "XI").
Variations for the lab test
- Display students of class XI or with marks below 60.
- Display the marks of students whose name starts with "A" (use
df["Name"].str[0] == "A"). - Count the rows in a filtered DataFrame with
len().
! Common mistake Writing
df[df["Marks"] > 60 & df["Class"] == "XII"] without brackets raises an error, because & is evaluated before >.