Drop columns whose name contains a specific string from pandas DataFrame
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
Dropping columns by name pattern is a common cleanup step in pandas workflows, especially after one-hot encoding, merged exports, or machine-generated feature sets. The main challenge is being precise enough to remove the intended columns without accidentally deleting similarly named data. A good solution starts by selecting matching column names explicitly, then dropping them in one clear operation.
Select Matching Columns Before Dropping
The safest pattern is to compute the columns you want to remove first. That makes the code easier to inspect and debug.
This approach is simple, readable, and works well when matching logic is straightforward.
Use String Methods on the Columns Index
Pandas exposes vectorized string operations on df.columns, which makes pattern matching concise.
Using regex=False is a good default when you want literal substring matching. It avoids surprises from regular expression metacharacters.
This form is especially convenient when you want to keep non-matching columns rather than build a drop list separately.
It also scales well when the DataFrame has many columns because the intent stays explicit: compute a boolean mask, then keep only the inverse of that mask.
Case-Insensitive Matching
Real datasets often contain inconsistent casing such as TempValue, temp_value, or TEMP_COL. Normalize casing before matching if needed.
This is safer than assuming naming conventions were applied consistently in upstream systems.
Regex Matching for More Control
When the rule is more specific than a plain substring, use a regex. For example, remove columns starting with tmp_.
Regex is powerful, but use it only when the rule needs that expressiveness. Literal substring matching is easier to maintain.
Drop In Place or Return a New Frame
Most pandas methods return a new DataFrame unless you explicitly mutate. In data pipelines, returning a new frame is usually easier to reason about.
If mutation is truly what you want:
Use inplace=True sparingly. It can make debugging and test setup harder because the original frame is no longer available for comparison.
Defensive Programming for Production Pipelines
In production code, add a small validation step before dropping columns so unexpected matches do not silently remove important data.
For important datasets, log both the matched columns and the remaining schema. That makes debugging upstream naming changes much easier.
Alternative: Keep Only Wanted Columns
Sometimes it is safer to define the columns you want to keep instead of pattern-dropping unknown columns. That is especially true in regulated or analytics-critical pipelines.
This is functionally similar, but it shifts the mental model from removal to whitelist selection. In some teams that is the more maintainable style.
Another pandas-specific variant uses filter to select the matching names first:
This is handy when you want pandas to do the name matching rather than writing the list comprehension yourself.
Common Pitfalls
- Forgetting
regex=Falseand accidentally treating the search string as a regular expression. - Using broad substrings and dropping columns that only partially match by coincidence.
- Modifying the original DataFrame in place when downstream code still expects old columns.
- Assuming column casing is consistent across all data sources.
- Dropping columns without logging what matched, which makes schema drift harder to debug.
Summary
- Compute matching column names explicitly before dropping them.
- Use
df.columns.str.containsfor concise, vectorized matching. - Prefer literal substring matching unless regex is truly required.
- Handle case sensitivity intentionally.
- Return a new DataFrame by default and use in-place mutation only when there is a clear reason.
Related reading
- Dropping infinite values from dataframes in pandas?
- Dummy variables when not all categories are present
- Dump a NumPy array into a csv file
- Dump a NumPy array into a csv file
- Drop data frame columns by name
- Duplicate log output when using Python logging module
- Duplicating training examples to handle class imbalance in a pandas data frame
- DynamicFrame vs DataFrame
.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.