- Filter rows in a DataFrame based on conditions
- Use boolean indexing to select specific rows
- Combine multiple conditions for complex filtering
Sample DataFrame
Let’s start with a sample DataFrame that we’ll use throughout this section:
id | name | age | city | salary |
---|---|---|---|---|
1 | Alice | 25 | New York | 50000 |
2 | Bob | 30 | San Francisco | 75000 |
3 | Carol | 35 | Chicago | 60000 |
4 | David | 40 | New York | 80000 |
5 | Emily | 28 | Chicago | 55000 |
Filtering Rows
Pandas provides powerful ways to filter rows based on conditions. We use boolean indexing to select rows that meet specific criteria.
Syntax
Exercise 2.1: Basic Filtering (Numbers)
Run the code below to filter the DataFrame and show only employees who are older than 30:
Exercise 2.2: Basic Filtering (Strings)
Modify the code below to filter the DataFrame and show only employees from Chicago:
Exercise 2.3: Filtering with AND (&)
Modify the code below to filter the DataFrame and show employees from New York with a salary greater than 60000:
Exercise 2.4: Filtering with OR (|)
Modify the code below to filter the DataFrame and show employees who are either from Chicago or have a salary less than 70000:
Exercise 2.5: Complex Filtering (Combining AND and OR)
Modify the code below to filter the DataFrame and show employees who are either from New York and older than 30, or have a salary greater than 70000:
Quiz
Loading...
Loading...
- Filter rows in a DataFrame using boolean indexing
- Use comparison operators (
>
,<
,==
, etc.) for filtering - Combine multiple conditions using
&
(and) and|
(or) operators - Create complex filters to select specific subsets of data