df.filter()'s name is a common source of confusion: unlike Python's built-in filter() or boolean indexing, which select rows based on their data values, df.filter() selects columns, by default, or rows based purely on their labels matching a criterion — items for an exact list of names, like for a substring contained in the label, or regex for a full pattern match. It's useful for quickly narrowing down to a group of similarly-named columns, like every column whose name starts with a common prefix.
1Understanding df.filter()
df.filter()'s name is a common source of confusion: unlike Python's built-in filter() or boolean indexing, which select rows based on their data values, df.filter() selects columns, by default, or rows based purely on their labels matching a criterion — items for an exact list of names, like for a substring contained in the label, or regex for a full pattern match. It's useful for quickly narrowing down to a group of similarly-named columns, like every column whose name starts with a common prefix.
Don't confuse df.filter() with filtering rows by a data condition — despite the name, filter() selects columns, or rows, by their labels matching a pattern, not by any actual data values; use boolean indexing or query() for value-based filtering instead.
import pandas as pd
df = pd.DataFrame({"sales_q1": [100], "sales_q2": [150], "region": ["East"]})
print(df.filter(like="sales"))2Practical Example
Here is a real-world application of df.filter() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"name": ["Alice"], "age": [30], "city": ["NYC"]})
print(df.filter(items=["name", "city"]))3Best Practices
Follow these guidelines when working with df.filter():
1. Use filter(like='prefix') or filter(regex=...) to quickly select a group of similarly-named columns, instead of manually listing them all out
2. Reach for boolean indexing or query() instead of filter() when the selection criterion is based on data values, not column/row names
3. Pass axis=0 explicitly when you want to filter rows by their index labels instead of the default column-label filtering
Tip: Don't confuse df.filter() with filtering rows by a data condition — despite the name, filter() selects columns, or rows, by their labels matching a pattern, not by any actual data values; use boolean indexing or query() for value-based filtering instead.
import pandas as pd
df = pd.DataFrame({"sales_q1": [100], "sales_q2": [150], "region": ["East"]})
print(df.filter(like="sales"))