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

Pandas Filtering and Conditional Queries

Pandas Filtering and Conditional Queries

Data filtering is one of the most commonly used operations in data analysis. Pandas provides rich conditional query features for filtering data by various conditions. This section describes various data filtering methods in detail.


Basic conditional filtering

Single-condition filtering

Example

import

pandas

as

pd

Create sample data

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Wang Wu"

,

"Zhao Liu"

,

"Qian Qi"

]

,

   

"Age"

:

[

25

,

30

,

28

,

35

,

22

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Guangzhou"

,

"Beijing"

,

"Shenzhen"

]

,

   

"Salary"

:

[

12000

,

15000

,

11000

,

18000

,

9000

]

,

   

"Department"

:

[

"Technology"

,

"Sales"

,

"Technology"

,

"Operations"

,

"Technology"

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Equality filtering

print

(

"City equals Beijing:"

)

print

(

df

[

df

[

"City"

]

==

"Beijing"

]

)

print

(

)

Inequality filtering

print

(

"City does not equal Beijing:"

)

print

(

df

[

df

[

"City"

]

!=

"Beijing"

]

)

print

(

)

Greater than and less than

print

(

"Salary greater than 12000:"

)

print

(

df

[

df

[

"Salary"

]

12000

]

)

print

(

)

String conditions

print

(

"Name contains 'three':"

)

print

(

df

[

df

[

"Name"

]

.

str

.

contains

(

Wed

)

]

)

Combining multiple conditions

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Wang Wu"

,

"Zhao Liu"

,

"Qian Qi"

]

,

   

"Age"

:

[

25

,

30

,

28

,

35

,

22

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Guangzhou"

,

"Beijing"

,

"Shenzhen"

]

,

   

"Salary"

:

[

12000

,

15000

,

11000

,

18000

,

9000

]

,

   

"Department"

:

[

"Technology"

,

"Sales"

,

"Technology"

,

"Operations"

,

"Technology"

]

}

)

AND condition: use the & symbol

print

(

"Beijing AND salary>10000:"

)

print

(

df

[

(

df

[

"City"

]

==

"Beijing"

)

&

(

df

[

"Salary"

]

10000

)

]

)

print

(

)

OR condition: use the | symbol

print

(

"Tech department OR salary>15000:"

)

print

(

df

[

(

df

[

"Department"

]

==

"Technology"

)

|

(

df

[

"Salary"

]

15000

)

]

)

print

(

)

NOT condition: use the ~ symbol

print

(

"Not the tech department:"

)

print

(

df

[

~

(

df

[

"Department"

]

==

"Technology"

)

]

)

print

(

)

Complex combinations

print

(

"(Beijing AND age>25) OR (Shanghai):"

)

print

(

df

[

(

(

df

[

"City"

]

==

"Beijing"

)

&

(

df

[

"Age"

]

25

)

)

|

(

df

[

"City"

]

==

"Shanghai"

)

]

)

When combining multiple conditions, each condition must be enclosed in parentheses, and the conditions must be connected using &(AND),|(or) between them; you cannot use Python's and、or The const keyword.


isin and where

Filtering with isin

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Wang Wu"

,

"Zhao Liu"

,

"Qian Qi"

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Guangzhou"

,

"Beijing"

,

"Shenzhen"

]

,

   

"Department"

:

[

"Technology"

,

"Sales"

,

"Technology"

,

"Operations"

,

"Technology"

]

}

)

Filter by a list

print

(

"City is Beijing or Shanghai:"

)

print

(

df

[

df

[

"City"

]

.

isin

(

[

"Beijing"

,

"Shanghai"

]

)

]

)

print

(

)

Not in a list

print

(

"City is neither Beijing nor Shanghai:"

)

print

(

df

[

~

df

[

"City"

]

.

isin

(

[

"Beijing"

,

"Shanghai"

]

)

]

)

print

(

)

isin on multiple columns

df2

=

pd.

DataFrame

(

{

   

"City"

:

[

"Beijing"

,

"Shanghai"

]

,

   

"Department"

:

[

"Technology"

,

"Sales"

]

}

)

print

(

"Satisfy both city and department:"

)

print

(

df

[

df

[

[

"City"

,

"Department"

]

]

.

isin

(

df2

)

.

all

(

axis

=

1

)

]

)

The where condition

Example

import

pandas

as

pd

import

numpy

as

np

df

=

pd.

DataFrame

(

{

   

"A"

:

[

1

,

5

,

3

,

7

]

,

   

"B"

:

[

4

,

2

,

8

,

3

]

}

)

where: keeps values that satisfy the condition and sets the others to NaN or a specified value

print

(

"Keep values greater than 3, set the others to 0:"

)

result

=

df.

where

(

df

3

,

0

)

print

(

result

)

print

(

)

Use another DataFrame as the condition

other

=

pd.

DataFrame

(

{

   

"A"

:

[

True

,

False

,

True

,

False

]

,

   

"B"

:

[

False

,

True

,

False

,

True

]

}

)

print

(

"Filter by a conditional DataFrame:"

)

print

(

df.

where

(

other

,

1

)

)


String filtering

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Wang Wu"

,

"Zhao Liu"

,

"Sun Qi"

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Guangzhou"

,

"Shenzhen"

,

"Hangzhou"

]

,

   

"email"

:

[

"zhangsan@email.com"

,

"lisi@email.com"

,

"wangwu@email.com"

,

             

"zhaoliu@email.com"

,

"sunqi@email.com"

]

}

)

Contains

print

(

"City contains 'Beijing':"

)

print

(

df

[

df

[

"City"

]

.

str

.

contains

(

"Beijing"

)

]

)

print

(

)

Start/End

print

(

"Email starts with zhang:"

)

print

(

df

[

df

[

"email"

]

.

str

.

startswith

(

"zhang"

)

]

)

print

(

)

Regex Matching

print

(

"Email username length greater than 4:"

)

print

(

df

[

df

[

"email"

]

.

str

.

extract

(

r

"(\w+)@"

)

[

0

]

.

str

.

len

(

)

4

]

)

print

(

)

Multiple Pattern Matching

print

(

"Cities starting with Bei, Shang, Guang, Shen:"

)

print

(

df

[

df

[

"City"

]

.

str

.

contains

(

"^Bei|^Shang|^Guang|^Shen"

)

]

)


Numeric Range Filtering

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Wang Wu"

,

"Zhao Liu"

,

"Qian Qi"

]

,

   

"Age"

:

[

25

,

30

,

28

,

35

,

22

]

,

   

"Salary"

:

[

12000

,

15000

,

11000

,

18000

,

9000

]

}

)

Range Filtering

print

(

"Age between 25 and 30 (inclusive):"

)

print

(

df

[

df

[

"Age"

]

.

between

(

25

,

30

)

]

)

print

(

)

Quantile Filtering

q1

=

df

[

"Salary"

]

.

quantile

(

0.25

)

q3

=

df

[

"Salary"

]

.

quantile

(

0.75

)

print

(

f

"Salary between 25% and 75% ({q1}-{q3}):"

)

print

(

df

[

df

[

"Salary"

]

.

between

(

q1

,

q3

)

]

)

print

(

)

Smallest/Largest N Rows

print

(

"Top 3 highest salaries:"

)

print

(

df.

nlargest

(

3

,

"Salary"

)

)

print

(

)

print

(

"Bottom 2 lowest salaries:"

)

print

(

df.

nsmallest

(

2

,

"Salary"

)

)


Time Series Data Filtering

Example

import

pandas

as

pd

Create time series data

df

=

pd.

DataFrame

(

{

   

"date"

: pd.

date_range

(

"2024-01-01"

,

periods

=

10

,

freq

=

"D"

)

,

   

"Sales"

:

[

100

,

120

,

90

,

150

,

200

,

180

,

110

,

130

,

170

,

190

]

}

)

df

=

df.

set_index

(

"date"

)

print

(

"Time series data:"

)

print

(

df

)

print

(

)

Filter by Date

print

(

"Data for 2024-01-05:"

)

print

(

df.

loc

[

"2024-01-05"

]

)

print

(

)

Date Range Filtering

print

(

"2024-01-03 to 2024-01-07:"

)

print

(

df.

loc

[

"2024-01-03"

:

"2024-01-07"

]

)

print

(

)

Using truncate (a more efficient slicing method)

print

(

"truncate filtering:"

)

print

(

df.

truncate

(

before

=

"2024-01-03"

,

after

=

"2024-01-07"

)

)


query Method

query The method provides a more concise, SQL-style way of filtering.

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Wang Wu"

,

"Zhao Liu"

]

,

   

"Age"

:

[

25

,

30

,

28

,

35

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Guangzhou"

,

"Beijing"

]

,

   

"Salary"

:

[

12000

,

15000

,

11000

,

18000

]

}

)

Using the query Method

print

(

"Age>26 and City='Beijing':"

)

print

(

df.

query

(

"Age > 26 and City == 'Beijing'"

)

)

print

(

)

Using variables

min_age

=

26

city

=

"Beijing"

print

(

f

"Age>{min_age} and City={city}:"

)

print

(

df.

query

(

"Age > @min_age and City == @city"

)

)

print

(

)

Use backticks when column names contain spaces

df2

=

df.

rename

(

columns

=

{

"Name"

:

"Surname Name"

}

)

print

(

"When a column name contains spaces:"

)

print

(

df2.

query

(

"姓 名 == 'Zhang San'

)

)


Common questions

1. Error with Combined Conditions

When filtering with multiple conditions, use parentheses to clarify precedence and use &、| instead of and、or。

2. String Contains Null Values

Use str.contains null values must be handled first:df[df["列"].str.contains("x", na=False)]

3. Index Filtering

If the DataFrame has a custom index, note the loc and iloc difference.

For complex multi-condition queries,query the method's syntax is closer to natural language, making the code more readable. When the data volume is large,loc combined with boolean arrays is usually query faster.