Filter pandas DataFrame by substring criteria
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
In pandas, substring filtering is usually done with the str accessor, most often str.contains. The important details are not the basic syntax but the edge cases: missing values, case sensitivity, whether the pattern should be treated as a regular expression, and whether you want contains, starts-with, or ends-with behavior.
Basic Substring Filtering
For “keep rows where a column contains some text,” use str.contains.
na=False matters. Without it, missing values can propagate NaN into the boolean mask and make filtering less predictable.
Case Sensitivity and Literal Matching
By default, str.contains is case-sensitive and treats the pattern as a regular expression.
That means these two questions are different:
- “does the text contain the literal string
C++” - “does the text match this regex pattern”
For a literal search, disable regex mode:
This is often the safest default when you are searching for ordinary user-provided text.
startswith and endswith
If the rule is positional rather than “contains anywhere,” use the dedicated helpers.
These methods are clearer than writing equivalent regular expressions by hand.
Filter Multiple Columns
Sometimes the substring can appear in more than one column. In that case, build a combined boolean mask.
Related reading
- Filter pandas DataFrame by substring criteria
- Filtering Pandas DataFrames on dates
- Find a series of data using non-exact measurements fuzzy logic
- Find column whose name contains a specific string
- Filtering a list based on a list of booleans
- Find all files in a directory with extension .txt in Python
- Find difference between two data frames
- Find element's index in pandas Series
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free 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.