How to filter Pandas dataframe using 'in' and 'not in' like in SQL
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Filtering data in a Pandas DataFrame is a common operation during data analysis tasks. Pandas, being a powerful tool, supports SQL-like querying, especially when it comes to filtering data using conditions such as in and not in. This article will guide you through using these conditions effectively within Pandas.
SQL IN and NOT IN in Pandas
The SQL IN is used to filter records where a field value matches any value within a list. Similarly, NOT IN is used to exclude records where a field value matches any value within a list. In Pandas, equivalent functionality can be achieved using the isin() method and boolean indexing.
Using isin() for SQL IN Like Filtering
The isin() method on a Pandas Series allows you to filter DataFrame rows where the column's value is present in a predefined list of values. Here’s how you can use it:
Example:
Suppose we have the following DataFrame:
If you want to filter the rows where the name is either 'Alice' or 'Bob', you can use isin() like this:
This will only include the rows where the 'Name' column matches 'Alice' or 'Bob'.
Inverting isin() for SQL NOT IN Like Filtering
To implement SQL’s NOT IN, you invert the boolean series returned by isin() using the ~ operator.
Example:
Continuing from the previous DataFrame, if you want to exclude 'Alice' and 'Bob':
This will exclude rows where the 'Name' column is either 'Alice' or 'Bob', thus including only 'Charlie' and 'David'.
Performance and Usage Tips
While using isin() is straightforward and powerful, there are certain scenarios where you might need to consider performance:
- Large DataFrames:
isin()can be slower on very large DataFrames. In such cases, converting the list to asetbefore passing it toisin()can sometimes improve performance since set lookups are generally faster than list. - Multiple Conditions: For multiple column filtering with
inandnot inconditions, ensure to carefully manage Boolean series using&(AND) and|(OR) with proper parentheses to avoid ambiguity in conditions.
Summary Table
| Method | SQL Equivalent | Description | Example |
isin() | IN | Filters rows where the column's values are in a provided list. | df[df['Name'].isin(['Alice', 'Bob'])] |
~ with isin() | NOT IN | Filters rows where the column's values are not in a provided list. | df[~df['Name'].isin(['Alice', 'Bob'])] |
Additional Points
- Combining Filters: These filters can be combined with other DataFrame operations to perform complex queries, such as sorting and grouping, after filtering.
- Alternative Methods: Alternatives like query methods or boolean indexing using
np.wherecan also be used depending primarily on readability preferences and specific use cases.
Understanding and efficiently implementing in and not in filters in Pandas parallel to their SQL counterparts, can greatly enhance your data manipulation and preprocessing capabilities in Python, leading to more robust and readable code.
Related reading
- How to filter Pandas dataframe using 'in' and 'not in' like in SQL
- How to filter rows containing a string pattern from a Pandas dataframe
- How to filter rows in pandas by regex
- How to find a columns set for a primary key candidate in CSV file?
- How to find a substring in a field in Mongodb
- How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?
- How to find a Python package's dependencies
- How to find all occurrences of an element in a list

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.