Pandas df.filter() function
filter() is a function in Pandas used to filter columns (rather than rows). It can select specific columns by column name, label pattern, or regular expression. Compared with loc[] and iloc[] in Vue 2,filter() it is specifically designed for column selection, which is very useful when working with datasets that have many columns.
In data analysis, sometimes we need to focus only on specific columns, such as selecting only numeric columns, only columns starting with a certain prefix, or only columns containing a certain keyword.filter() is designed exactly for these scenarios.
Basic syntax and parameters
filter() is a method of DataFrame and Series (for Series, only the items parameter is supported) used to filter columns by conditions.
Syntax format
DataFrame.filter(items=None, like=None, regex=None, axis=None)
Parameter Description
| Parameters | Type | Required | Description | Default value |
|---|---|---|---|---|
| items | list | Optional | Directly specify a list of column names to select matching columns. | None |
| like | str | Optional | Column names containing a specified string, supporting fuzzy matching. | None |
| regex | str | Optional | A regular expression pattern to match column names. | None |
| axis | int or str | Optional | The axis to filter. 0 or 'index' means rows, 1 or 'columns' means columns. | 1 or 'columns' |
Return value description
- Return value type: Returns a new DataFrame containing the filtered columns.
- Column filtering: By default,
filter()operates on columns (axis=1). - All rows are kept: Filtering only affects columns; row data remains unchanged.
Example
Let us fully master it through a wealth of examples filter() through a series of examples from simple to complex.
Example 1: Basic usage - using the items parameter
Directly specify a list of column names to select specific columns.
Example
import
pandas
as
pd
Create a sample DataFrame
data
=
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
]
,
'age'
:
[
18
,
19
,
17
,
18
,
20
]
,
'score'
:
[
85
,
92
,
78
,
90
,
88
]
,
'grade'
:
[
'A'
,
'A'
,
'B'
,
'A'
,
'B'
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Beijing'
,
'Guangzhou'
,
'Shanghai'
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original DataFrame:"
)
(
df
)
(
)
Use the items parameter to select specific columns
(
"Selecting the name and age columns:"
)
(
df.
filter
(
items
=
[
'name'
,
'age'
]
)
)
(
)
Select a single column (returns a DataFrame)
(
"Selecting only the score column:"
)
(
df.
filter
(
items
=
[
'score'
]
)
)
Running result:
原始 DataFrame:
name age score grade city
0 Alice 18 85 A Beijing
1 Bob 19 92 A Shanghai
2 Charlie 17 78 B Beijing
3 David 18 90 A Guangzhou
4 Eve 20 88 B Shanghai
Select the name and age columns:
name age
0 Alice 18
1 Bob 19
2 Charlie 17
3 David 18
4 Eve 20
# Select only the score column:
score
0 85
1 92
2 78
3 90
4 88
Code analysis:
filter(items=['name', 'age'])Select the specified columns and return a new DataFrame containing them.- All rows are kept; only specific columns are selected.
- If a specified column name does not exist, a KeyError is raised.
Example 2: Using the like parameter - fuzzy matching
like The parameter allows us to filter columns whose names contain a specified string, which is ideal for datasets with regularly patterned column names.
Example
import
pandas
as
pd
Create a DataFrame with regularly patterned column names
data
=
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
]
,
'age_2020'
:
[
18
,
19
,
17
,
18
,
20
]
,
'age_2021'
:
[
19
,
20
,
18
,
19
,
21
]
,
'age_2022'
:
[
20
,
21
,
19
,
20
,
22
]
,
'score_2020'
:
[
85
,
92
,
78
,
90
,
88
]
,
'score_2021'
:
[
87
,
94
,
80
,
92
,
90
]
,
'score_2022'
:
[
89
,
96
,
82
,
94
,
92
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Beijing'
,
'Guangzhou'
,
'Shanghai'
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original DataFrame:"
)
(
df
)
(
)
Select all columns containing "age"
(
"Columns containing 'age':"
)
(
df.
filter
(
like
=
'age'
)
)
(
)
Select all columns containing "score"
(
"Columns containing 'score':"
)
(
df.
filter
(
like
=
'score'
)
)
(
)
Select all columns containing "2021"
(
"Columns containing '2021':"
)
(
df.
filter
(
like
=
'2021'
)
)
Running result:
原始 DataFrame:
name age_2020 age_2021 age_2022 score_2020 score_2021 score_2022 city
0 Alice 18 19 20 85 87 89 Beijing
1 Bob 19 20 21 92 94 96 Shanghai
2 Charlie 17 18 19 78 80 82 Beijing
3 David 18 19 20 90 92 94 Guangzhou
4 Eve 20 21 22 88 90 92 Shanghai
Columns containing 'age':
age_2020 age_2021 age_2022
0 18 19 20
1 19 20 21
2 17 18 19
3 18 19 20
4 20 21 22
Columns containing 'score':
score_2020 score_2021 score_2022
0 85 87 89
1 92 94 96
2 78 80 82
3 90 92 94
4 88 90 92
Columns containing '2021':
age_2021 score_2021
0 19 87
1 20 94
2 18 80
3 19 92
4 21 90
Code analysis:
filter(like='age')Select all columns whose names contain "age".- Fuzzy matching does not require knowing the full column name; just provide a partial match string.
- This is especially useful when working with columns that follow a similar naming convention, such as columns organized by year.
Example 3: Using the regex parameter - regular expression matching
For more complex column name filtering needs, you can use regular expressions.
Example
import
pandas
as
pd
Create complex column names
data
=
{
'id'
:
[
1
,
2
,
3
,
4
,
5
]
,
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
]
,
'age_2020'
:
[
18
,
19
,
17
,
18
,
20
]
,
'age_2021'
:
[
19
,
20
,
18
,
19
,
21
]
,
'score_math'
:
[
85
,
92
,
78
,
90
,
88
]
,
'score_english'
:
[
87
,
94
,
80
,
92
,
90
]
,
'score_science'
:
[
89
,
96
,
82
,
94
,
92
]
,
'city'
:
[
'Beijing'
,
'Shanghai'
,
'Beijing'
,
'Guangzhou'
,
'Shanghai'
]
}
df
=
pd.
DataFrame
(
data
)
(
"Columns of the original DataFrame:"
)
(
df.
columns
.
tolist
(
)
)
(
)
Select columns starting with "score_"
(
"Columns starting with 'score_':"
)
(
df.
filter
(
regex
=
'^score_'
)
)
(
)
Select column names containing digits
(
"Column names containing digits:"
)
(
df.
filter
(
regex
=
'\d'
)
)
d matches digits
(
)
Select columns containing both "age" and "202"
(
"Columns containing 'age' and '202':"
)
(
df.
filter
(
regex
=
'age.*202|202.*age'
)
)
(
)
Select columns that start with a letter and contain no underscore
(
"Columns starting with a letter and containing no underscore:"
)
(
df.
filter
(
regex
=
'^[a-zA-Z]+$'
)
)
Running result:
Columns of the original DataFrame:
['id', 'name', 'age_2020', 'age_2021', 'score_math', 'score_english', 'score_science', 'city']
Columns starting with 'score_':
score_math score_english score_science
0 85 87 89
1 92 94 96
2 78 80 82
3 90 92 94
4 88 90 92
Column names containing numbers:
age_2020 age_2021 score_math score_english score_science
0 18 19 85 87 89
1 19 20 92 94 96
2 17 18 78 80 82
3 18 19 90 92 94
4 20 21 88 90 92
Columns containing 'age' and '202':
age_2020 age_2021
0 18 19
1 19 20
2 17 18
3 18 19
4 20 21
Columns starting with a letter and not containing underscores:
name city
0 Alice Beijing
1 Bob Shanghai
2 Charlie Beijing
3 David Guangzhou
4 Eve Shanghai
Code analysis:
filter(regex='^score_')Use^Matches columns starting with "score_".filter(regex='\d')Use\dMatches column names containing digits.- Regular expressions offer the greatest flexibility and can handle a wide variety of complex matching needs.
Example 4: Using the axis parameter to filter rows
Although filter() is mainly used for columns, but through the axis parameter it can also be used to filter rows.
Example
import
pandas
as
pd
Create a DataFrame with a named index
data
=
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
,
'David'
,
'Eve'
]
,
'age'
:
[
18
,
19
,
17
,
18
,
20
]
,
'score'
:
[
85
,
92
,
78
,
90
,
88
]
}
df
=
pd.
DataFrame
(
data
,
index
=
[
'row1'
,
'row2'
,
'row3'
,
'row4'
,
'row5'
]
)
(
"DataFrame with a named index:"
)
(
df
)
(
)
Use axis='index' to filter rows (using like)
(
"Rows whose index contains 'row':"
)
(
df.
filter
(
like
=
'row'
,
axis
=
'index'
)
)
(
)
Use items to filter rows with specific indices
(
"Rows with index 'row1' and 'row3':"
)
(
df.
filter
(
items
=
[
'row1'
,
'row3'
]
,
axis
=
'index'
)
)
(
)
Use regex to filter rows
(
"Rows whose index matches the regular expression (row[135]):"
)
(
df.
filter
(
regex
=
'row[135]'
,
axis
=
'index'
)
)
Running result:
带命名索引的 DataFrame:
name age score
row1 Alice 18 85
row2 Bob 19 92
row3 Charlie 17 78
row4 David 18 90
row5 Eve 20 88
Rows containing 'row' in the index:
name age score
row1 Alice 18 85
row2 Bob 19 92
row3 Charlie 17 78
row4 David 18 90
row5 Eve 20 88
Rows with index 'row1' and 'row3':
name age score
row1 Alice 18 85
row3 Charlie 17 78
Rows whose index matches the regular expression (row[135]):
name age score
row1 Alice 18 85
row3 Charlie 17 78
row5 Eve 20 88
Code analysis:
axis='index'oraxis=0Tellsfilter()to filter row indices.like、items、regexThe parameter is used the same way for row filtering as for column filtering.- This is very useful when you need to filter specific rows by index name.
Example 5: Combining with other functions
filter() can be combined with other Pandas functions to achieve powerful data selection.
Example
import
pandas
as
pd
import
numpy
as
np
Create a large DataFrame
np.
random
.
seed
(
42
)
df
=
pd.
DataFrame
(
np.
random
.
randn
(
5
,
10
)
,
columns
=
[
'A'
,
'B'
,
'C'
,
'D'
,
'E'
,
'AA'
,
'BB'
,
'CC'
,
'DD'
,
'EE'
]
)
(
"Columns of the original DataFrame:"
)
(
df.
columns
.
tolist
(
)
)
(
)
Filter single-letter columns and perform calculations
single_letter_cols
=
df.
filter
(
regex
=
'^[A-E]$'
)
(
"Mean of single-letter columns (A-E):"
)
(
single_letter_cols.
mean
(
)
)
(
)
Filter two-letter columns and perform calculations
double_letter_cols
=
df.
filter
(
regex
=
'^[A-E]{2}$'
)
(
"Mean of two-letter columns (AA-EE):"
)
(
double_letter_cols.
mean
(
)
)
(
)
Filter columns first, then select rows
(
"First 3 rows of the two-letter columns:"
)
(
df.
filter
(
regex
=
'^[A-E]{2}$'
)
.
head
(
3
)
)
Running result:
Columns of the original DataFrame:
['A', 'B', 'C', 'D', 'E', 'AA', 'BB', 'CC', 'DD', 'EE']
Mean of single-letter columns (A-E):
A 0.336744
B 0.128223
C -0.234007
D -0.347540
E -0.197939
dtype: float64
Mean of the two-letter columns (AA-EE):
AA 0.530256
BB -0.671336
CC 0.506853
DD -0.443588
EE -0.456486
dtype: float64
The first 3 rows of the two-letter column:
AA BB CC DD EE
0 -0.013497 -1.174139 0.214864 1.550698 0.375698
1 -1.368593 0.746580 0.669383 -0.717552 -1.159950
2 0.602619 -1.700736 -0.201647 -0.605166 -0.012750
Code analysis:
filter()can be chained with other DataFrame methods.- Filter specific columns first, then perform statistical calculations, improving code readability.
- This is especially useful when working with wide tables.
Notes
itemsis used to precisely specify column names,likeis used for fuzzy matching,regexis used for regular expression matching. Choose the appropriate approach based on actual needs.- When working with large datasets, first using
filter()to filter the needed columns can reduce the amount of data for subsequent calculations and improve performance. filter()operates on columns by default (axis=1), and you canaxis='index'oraxis=0to change the filtering direction.- Note
items、like、regexThese three parameters are mutually exclusive and cannot be used together.
Tip:
filter()is a powerful tool for working with wide tables (datasets with many columns). Especially during the data exploration phase, if you only want to focus on a certain kind of information (such as all numeric columns or all columns starting with a certain prefix), usingfilter()can quickly accomplish column filtering.
Summary
filter() is a function in Pandas specifically for filtering columns (and rows). It provides three filtering approaches: precise specification (items), fuzzy matching (like), and regular expression matching (regex).
The main application scenarios of this function include: filtering specific columns, handling columns with regular naming conventions, and dynamically selecting columns to analyze. Combined with other Pandas functions, it can significantly improve data processing efficiency and code readability.
Common Pandas functions