Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 13

Pandas: Filtering and Selecting Data

This lesson is built with resources from pandas.pydata.org and consoleflare.com.

Hello! Welcome to the next lesson in our "Python Tools for AI and Data Manipulation" module.

In our previous session, you learned the critical first steps of data preprocessing: handling missing values with methods like .fillna() and correcting data types with pd.to_numeric() and .astype(). This ensures our dataset is clean, consistent, and ready for analysis.

Now that our data is in good shape, we can start asking questions and extracting insights. To do that, we need to select specific subsets of the data. This lesson focuses on that exact skill, addressing the learning outcome: Perform data filtering and selection using Pandas.

As a software engineer, you can think of this as learning the query language for DataFrames. Just as you might use SQL to select specific records from a database table, you'll use Pandas' indexing and filtering tools to select specific rows and columns from a DataFrame.

We'll cover three main areas:

  1. Basic Selection: How to grab specific columns or rows using their names or positions.
  2. Conditional Filtering: The most common task—filtering rows based on the values in their columns.
  3. Advanced Methods: Convenient and powerful ways to filter data, such as .query() and .isin().

1. Basic Selection: Columns and Rows

Before we filter, let's cover the basics of selecting data. The primary tools for this are the square brackets [] and the powerful .loc[] and .iloc[] indexers.

For a comprehensive guide, the official Pandas documentation is the ultimate source of truth. We will refer to it throughout this lesson.

Indexing and selecting data — pandas 3.0.0 documentation

Let's start by looking at the official Pandas guide on indexing. It introduces the main tools we'll be discussing.

Skim the sections 'Different choices for indexing', 'Basics', 'Attribute access', and 'Slicing ranges'. Don't worry about memorizing everything; focus on understanding the fundamental difference between selecting columns with [] and the purpose of .loc and .iloc.

Here’s a summary of the most important points from the reading:

Selecting Columns

You have two common ways to select one or more columns:

  1. Using square brackets []:

    • To select a single column, pass its name as a string. This returns a Pandas Series.
      # df['column_name'] -> returns a Series
      
    • To select multiple columns, pass a list of strings. This returns a new DataFrame.
      # df[['col1', 'col2', 'col3']] -> returns a DataFrame
      
  2. Using attribute access (.):

    • For columns with names that are valid Python identifiers (no spaces, special characters, etc.), you can use dot notation.
      # df.column_name
      
    • Caution: This is convenient but less robust. It won't work if the column name conflicts with a built-in DataFrame method (e.g., df.count) or isn't a valid identifier (df.total sales). It's generally safer to use the [] notation, especially in production code.

Selecting Rows and Columns with .loc[] and .iloc[]

While [] is great for columns, it's less explicit for rows. For robust row and column selection, Pandas provides two dedicated indexers:

  • .loc[]: Label-based selection. You use the actual names/labels of the index and columns.
  • .iloc[]: Integer-position-based selection. You use the integer index (from 0 to length-1), just like with Python lists.
Pandas iloc Method Syntax Breakdown
This image breaks down the syntax for `.iloc[]`. The same structure `[rows, columns]` applies to `.loc[]`, but you use labels instead of integer positions.

Let's see how they compare:

Operation Using .loc[] (Label-based) Using .iloc[] (Position-based)
Select a single row df.loc['row_label'] df.iloc[0]
Select multiple rows df.loc[['label1', 'label2']] df.iloc[[0, 2, 5]]
Slice rows df.loc['start':'end'] (inclusive) df.iloc[0:5] (exclusive of end)
Select rows and columns df.loc['row_label', 'col_label'] df.iloc[0, 1]
Slice rows and columns df.loc['start_r':'end_r', 'start_c':'end_c'] df.iloc[0:5, 0:2]

The distinction between inclusive slicing in .loc[] and exclusive slicing in .iloc[] is a classic "gotcha" but is consistent with their respective paradigms: labels vs. Python-style integer positions.


2. Conditional Filtering with Boolean Indexing

This is the most powerful and common way to filter data. The idea is to create a boolean Series (a list of True/False values) based on a condition, and then use that Series to select the rows from the DataFrame where the value is True.

Let's create a sample DataFrame to work with.

import pandas as pd

data = {
    'employee_id': [101, 102, 103, 104, 105, 106],
    'department': ['Sales', 'IT', 'IT', 'Marketing', 'Sales', 'IT'],
    'salary': [70000, 85000, 92000, 65000, 72000, 110000],
    'years_at_company': [3, 5, 6, 2, 4, 8]
}
df = pd.DataFrame(data)

Simple Boolean Condition

To select all employees from the 'IT' department:

# 1. This creates the boolean Series
is_it = df['department'] == 'IT'
print(is_it)
# 0    False
# 1     True
# 2     True
# 3    False
# 4    False
# 5     True
# Name: department, dtype: bool

# 2. Use this Series to filter the DataFrame
it_employees = df[is_it]
print(it_employees)

You will almost always see this written in a single line:

it_employees = df[df['department'] == 'IT']

Combining Multiple Conditions

To combine conditions, you must use the bitwise operators & (and), | (or), and ~ (not). Crucially, each condition must be wrapped in parentheses () due to Python's operator precedence. Forgetting the parentheses is a very common error.

Pandas Data Filtering with Multiple Columns Example
This image illustrates the pattern of creating and combining boolean masks to filter a DataFrame, a fundamental technique.

For example, let's find employees in the 'IT' department with a salary over $90,000.

high_earning_it = df[(df['department'] == 'IT') & (df['salary'] > 90000)]
print(high_earning_it)
#    employee_id department  salary  years_at_company
# 2          103         IT   92000                 6
# 5          106         IT  110000                 8

To find employees in 'Sales' OR 'Marketing':

sales_or_marketing = df[(df['department'] == 'Sales') | (df['department'] == 'Marketing')]
print(sales_or_marketing)

The ConsoleFlare blog post provides more straightforward examples of these common filtering patterns.

Data Filtering & Querying in Pandas: Essential Tips & Tricks

This blog post, 'Data Filtering & Querying in Pandas', offers quick and clear code snippets for the most common filtering operations.

Read the sections 'Basics of Data Filtering' and 'Conditional Filtering with Multiple Conditions'. Notice how the code is structured, especially the use of parentheses when combining conditions.


3. Advanced and Convenient Filtering Methods

While boolean indexing is the workhorse, Pandas provides several other methods that can make your code more readable and concise.

The .isin() Method

When you need to check if a column's value is in a list of allowed values, using | can get clumsy. The .isin() method is perfect for this.

Instead of this:

df[(df['department'] == 'Sales') | (df['department'] == 'Marketing')]

You can write this:

allowed_depts = ['Sales', 'Marketing']
df[df['department'].isin(allowed_depts)]

The .query() Method

This method allows you to filter a DataFrame using a string expression, which can be highly readable, especially for complex queries. This might feel familiar to you given your experience with databases.

The query for high-earning IT employees becomes:

df.query("department == 'IT' and salary > 90000")

Notice that you don't need to reference the df inside the string. You can also reference external variables by prefixing them with @:

min_salary = 90000
df.query("department == 'IT' and salary > @min_salary")

This makes your code clean and your filtering logic very explicit.

Using .loc for Simultaneous Filtering and Selection

A very common task is to filter rows based on a condition and select specific columns from those rows. The most robust way to do this is with .loc[].

# Get the 'employee_id' and 'salary' for employees with more than 5 years at the company
long_term_employees_info = df.loc[df['years_at_company'] > 5, ['employee_id', 'salary']]
print(long_term_employees_info)
#    employee_id  salary
# 2          103   92000
# 5          106  110000

The syntax is df.loc[row_condition, column_list].

Using .loc[] is the recommended best practice. While you might see df[df['years_at_company'] > 5][['employee_id', 'salary']] (called "chained indexing"), this can sometimes lead to unpredictable behavior, especially when you are trying to assign new values. Using .loc[] is explicit and guaranteed to work as expected.

Indexing and selecting data — pandas 3.0.0 documentation

Let's revisit the Pandas documentation to solidify our understanding of these powerful techniques.

Now, read the sections on 'Boolean indexing', 'Indexing with isin', and 'The query() Method'. Try to connect these formal explanations with the examples we just discussed.

Test your understanding!

Using the df DataFrame we defined earlier, complete the following tasks:

  1. Select the salary for the employee with employee_id 104.
  2. Find all employees who are not in the 'IT' department.
  3. Find all employees in the 'Sales' department who have been with the company for 3 years or more.
  4. Solve task #3 again, but this time using the .query() method.
Show answer

Here are the solutions:

# Setup DataFrame
import pandas as pd
data = {'employee_id': [101, 102, 103, 104, 105, 106],
        'department': ['Sales', 'IT', 'IT', 'Marketing', 'Sales', 'IT'],
        'salary': [70000, 85000, 92000, 65000, 72000, 110000],
        'years_at_company': [3, 5, 6, 2, 4, 8]}
df = pd.DataFrame(data).set_index('employee_id') # Setting index for easier .loc access by ID

# 1. Select salary for employee_id 104
# We use .loc because employee_id is now the index (a label)
salary_104 = df.loc[104, 'salary']
print(f"Salary for employee 104: {salary_104}\n")

# 2. Find all employees not in the 'IT' department
# Use boolean indexing with the '~' (not) operator
not_it = df[~(df['department'] == 'IT')]
print("Employees not in IT:\n", not_it, "\n")

# 3. Find Sales employees with >= 3 years
# Combine two conditions with '&'
long_term_sales = df[(df['department'] == 'Sales') & (df['years_at_company'] >= 3)]
print("Long-term Sales employees:\n", long_term_sales, "\n")

# 4. Solve task #3 using .query()
long_term_sales_query = df.query("department == 'Sales' and years_at_company >= 3")
print("Long-term Sales employees (using query):\n", long_term_sales_query, "\n")

Conclusion

You now have a powerful toolkit for selecting and filtering data in Pandas. Mastering these operations is fundamental to all data analysis and feature engineering tasks that lie ahead in your AI journey.

Key Takeaways:

  • Use [] for quick and simple column selection.
  • Use .loc[] for label-based selection and .iloc[] for integer position-based selection. They are your most robust tools for selecting specific rows and columns.
  • Boolean indexing (df[condition]) is the primary method for filtering data based on its values.
  • Always wrap combined conditions in parentheses and use &, |, and ~.
  • For cleaner code, leverage convenience methods like .isin() for multiple value checks and .query() for readable, SQL-like expressions.
  • The df.loc[row_condition, column_list] pattern is the best practice for filtering rows and selecting columns in a single, explicit step.

Next up:
Now that we can isolate specific groups of data (e.g., all employees in the 'IT' department), the next logical step is to perform calculations on these groups. In the next lesson, we will explore grouping and aggregation, which allows us to answer questions like, "What is the average salary for each department?" We will learn to use the powerful .groupby() method to unlock deeper insights.