Mathew K Analytics

Lesson 19 · Mastering Pandas

Mastering Conditional Selection & Boolean Indexing in Pandas for Data Analysis

Welcome! In this lesson, you are going to master conditional selection and boolean indexing in pandas. We will use the Titanic Dataset to practice real…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Intermediate Pandas: Conditional Selection and Boolean Indexing#

Welcome! In this lesson, you are going to master conditional selection and boolean indexing in pandas.

We will use the Titanic Dataset to practice real filtering and exploration.

By the end, you will know how to select rows and columns using conditions, combine multiple conditions, and use boolean masks for flexible data selection.

import warnings; warnings.filterwarnings('ignore')
# Data setup (Titanic Dataset)
import pandas as pd
import numpy as np
np.random.seed(42)
url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv'
df = pd.read_csv(url)
print(df.shape)
print(df.head(3))
(891, 12)
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   

   Parch            Ticket     Fare Cabin Embarked  
0      0         A/5 21171   7.2500   NaN        S  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  

Why Learn Conditional Selection?#

Conditional selection lets you focus on data that meets specific rules.

For example, you might want to find all passengers in First Class or all survivors.

This is the foundation for most data analysis in pandas.

# Select all passengers who survived
survived = df[df['Survived'] == 1]
print(survived.head(3))
   PassengerId  Survived  Pclass  \
1            2         1       1   
2            3         1       3   
3            4         1       1   

                                                Name     Sex   Age  SibSp  \
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female  35.0      1   

   Parch            Ticket     Fare Cabin Embarked  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  
3      0            113803  53.1000  C123        S  
# Select all children (under 18 years old)
kids = df[df['Age'] < 18]
print(kids[['Name','Age']].head(3))
                                   Name   Age
7        Palsson, Master. Gosta Leonard   2.0
9   Nasser, Mrs. Nicholas (Adele Achem)  14.0
10      Sandstrom, Miss. Marguerite Rut   4.0
# Combine multiple conditions: Female passengers in First Class
first_class_women = df[(df['Sex'] == 'female') & (df['Pclass'] == 1)]
print(first_class_women[['Name','Sex','Pclass']].head(3))
                                                 Name     Sex  Pclass
1   Cumings, Mrs. John Bradley (Florence Briggs Th...  female       1
3        Futrelle, Mrs. Jacques Heath (Lily May Peel)  female       1
11                           Bonnell, Miss. Elizabeth  female       1
# Use OR logic with | to select male passengers OR children
men_or_kids = df[(df['Sex'] == 'male') | (df['Age'] < 18)]
print(men_or_kids[['Name','Sex','Age']].head(3))
                       Name   Sex   Age
0   Braund, Mr. Owen Harris  male  22.0
4  Allen, Mr. William Henry  male  35.0
5          Moran, Mr. James  male   NaN
# Select rows using isin for multiple values
third_or_first = df[df['Pclass'].isin([1,3])]
print(third_or_first[['Name','Pclass']].head(3))
                                                Name  Pclass
0                            Braund, Mr. Owen Harris       3
1  Cumings, Mrs. John Bradley (Florence Briggs Th...       1
2                             Heikkinen, Miss. Laina       3
# Invert a condition with ~ (tilde)
not_survived = df[~(df['Survived'] == 1)]
print(not_survived[['Name','Survived']].head(3))
                       Name  Survived
0   Braund, Mr. Owen Harris         0
4  Allen, Mr. William Henry         0
5          Moran, Mr. James         0

Boolean Masks and Saving Them#

You can save a filter as a mask for repeated use. This helps with more complex filtering and for explanations.

Lets create a mask for adults in Second Class.

# Create a boolean mask and reuse it
mask = (df['Age'] >= 18) & (df['Pclass'] == 2)
adults_second = df[mask]
print(adults_second[['Name','Age','Pclass']].head(3))
                                Name   Age  Pclass
15  Hewlett, Mrs. (Mary D Kingcome)   55.0       2
20              Fynney, Mr. Joseph J  35.0       2
21             Beesley, Mr. Lawrence  34.0       2
# Select rows where the Name contains 'Mrs.'
mrs = df[df['Name'].str.contains('Mrs.')]
print(mrs[['Name','Sex']].head(3))
                                                Name     Sex
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female
8  Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)  female
# Use isnull to find missing Ages
missing_age = df[df['Age'].isnull()]
print(missing_age[['Name','Age']].head(3))
                            Name  Age
5               Moran, Mr. James  NaN
17  Williams, Mr. Charles Eugene  NaN
19       Masselmani, Mrs. Fatima  NaN
# Using query for readable conditions
over40women = df.query('Sex == "female" and Age > 40')
print(over40women[['Name','Age','Sex']].head(3))
                                        Name   Age     Sex
11                  Bonnell, Miss. Elizabeth  58.0  female
15          Hewlett, Mrs. (Mary D Kingcome)   55.0  female
52  Harper, Mrs. Henry Sleeper (Myna Haxtun)  49.0  female
# Find all passengers with fares between 50 and 100 (inclusive)
mid_fares = df[(df['Fare'] >= 50) & (df['Fare'] <= 100)]
print(mid_fares[['Name','Fare']].head(3))
                                                Name     Fare
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  71.2833
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  53.1000
6                            McCarthy, Mr. Timothy J  51.8625
# Use .loc to select by condition and pick columns
survived_names = df.loc[df['Survived'] == 1, ['Name','Sex','Pclass']]
print(survived_names.head(3))
                                                Name     Sex  Pclass
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female       1
2                             Heikkinen, Miss. Laina  female       3
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female       1
# Use .copy to avoid SettingWithCopyWarning
subset = df[df['Pclass'] == 3].copy()
subset['Deck'] = subset['Cabin'].str[0]
print(subset[['Name','Cabin','Deck']].head(3))
                       Name Cabin Deck
0   Braund, Mr. Owen Harris   NaN  NaN
2    Heikkinen, Miss. Laina   NaN  NaN
4  Allen, Mr. William Henry   NaN  NaN
# Use input to select a passenger name to look up
search_name = input('Enter a name keyword to search for: ')
found = df[df['Name'].str.contains(search_name, case=False)]
print(found[['Name','Survived','Pclass']].head(5))
                                                  Name  Survived  Pclass
8    Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)         1       3
172                       Johnson, Miss. Eleanor Ileen         1       3
302                    Johnson, Mr. William Cahoone Jr         0       3
597                                Johnson, Mr. Alfred         0       3
719                       Johnson, Mr. Malkolm Joackim         0       3
# Challenge: Find all passengers NOT in Third Class, under 30, and who survived
challenge = df[(df['Pclass'] != 3) & (df['Age'] < 30) & (df['Survived'] == 1)]
print(challenge[['Name','Age','Pclass','Survived']].head(3))
                                        Name   Age  Pclass  Survived
9        Nasser, Mrs. Nicholas (Adele Achem)  14.0       2         1
23              Sloper, Mr. William Thompson  28.0       1         1
43  Laroche, Miss. Simonne Marie Anne Andree   3.0       2         1

Practice Time#

Now it is your turn! Try filtering for:

  • All siblings traveling together (siblings > 0)
  • Any passenger with 'Master.' in their name
  • People with fares above 200

Pause here to explore. Which group is the largest?

Recap: Mastering Conditional Selection in Pandas#

You practiced basic and advanced filtering, combined rules, and used masks.

With these skills, you can answer real-world questions and spot trends in any dataset.

Conditional selection is a superpower for analysts and data scientists.

What Will You Explore Next?#

Like this lesson? Give this video a thumbs up and subscribe for more hands-on pandas tutorials!

Comment below: What data question will you try solving with conditional selection?

Happy coding!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.