Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas df.filter() function

Pandas df.filter() function

Pandas Common Functions Common Pandas functions


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


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

)

print

(

"Original DataFrame:"

)

print

(

df

)

print

(

)

Use the items parameter to select specific columns

print

(

"Selecting the name and age columns:"

)

print

(

df.

filter

(

items

=

[

'name'

,

'age'

]

)

)

print

(

)

Select a single column (returns a DataFrame)

print

(

"Selecting only the score column:"

)

print

(

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:

  1. filter(items=['name', 'age']) Select the specified columns and return a new DataFrame containing them.
  2. All rows are kept; only specific columns are selected.
  3. 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

)

print

(

"Original DataFrame:"

)

print

(

df

)

print

(

)

Select all columns containing "age"

print

(

"Columns containing 'age':"

)

print

(

df.

filter

(

like

=

'age'

)

)

print

(

)

Select all columns containing "score"

print

(

"Columns containing 'score':"

)

print

(

df.

filter

(

like

=

'score'

)

)

print

(

)

Select all columns containing "2021"

print

(

"Columns containing '2021':"

)

print

(

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:

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

)

print

(

"Columns of the original DataFrame:"

)

print

(

df.

columns

.

tolist

(

)

)

print

(

)

Select columns starting with "score_"

print

(

"Columns starting with 'score_':"

)

print

(

df.

filter

(

regex

=

'^score_'

)

)

print

(

)

Select column names containing digits

print

(

"Column names containing digits:"

)

print

(

df.

filter

(

regex

=

'\d'

)

)

 

d matches digits

print

(

)

Select columns containing both "age" and "202"

print

(

"Columns containing 'age' and '202':"

)

print

(

df.

filter

(

regex

=

'age.*202|202.*age'

)

)

print

(

)

Select columns that start with a letter and contain no underscore

print

(

"Columns starting with a letter and containing no underscore:"

)

print

(

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:

  1. filter(regex='^score_') Use ^ Matches columns starting with "score_".
  2. filter(regex='\d') Use \d Matches column names containing digits.
  3. 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'

]

)

print

(

"DataFrame with a named index:"

)

print

(

df

)

print

(

)

Use axis='index' to filter rows (using like)

print

(

"Rows whose index contains 'row':"

)

print

(

df.

filter

(

like

=

'row'

,

axis

=

'index'

)

)

print

(

)

Use items to filter rows with specific indices

print

(

"Rows with index 'row1' and 'row3':"

)

print

(

df.

filter

(

items

=

[

'row1'

,

'row3'

]

,

axis

=

'index'

)

)

print

(

)

Use regex to filter rows

print

(

"Rows whose index matches the regular expression (row[135]):"

)

print

(

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:

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'

]

)

print

(

"Columns of the original DataFrame:"

)

print

(

df.

columns

.

tolist

(

)

)

print

(

)

Filter single-letter columns and perform calculations

single_letter_cols

=

df.

filter

(

regex

=

'^[A-E]$'

)

print

(

"Mean of single-letter columns (A-E):"

)

print

(

single_letter_cols.

mean

(

)

)

print

(

)

Filter two-letter columns and perform calculations

double_letter_cols

=

df.

filter

(

regex

=

'^[A-E]{2}$'

)

print

(

"Mean of two-letter columns (AA-EE):"

)

print

(

double_letter_cols.

mean

(

)

)

print

(

)

Filter columns first, then select rows

print

(

"First 3 rows of the two-letter columns:"

)

print

(

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:


Notes

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), using filter() 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.

Pandas Common Functions Common Pandas functions