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"
]
}
)
(
"Original data:"
)
(
df
)
(
)
Equality filtering
(
"City equals Beijing:"
)
(
df
[
df
[
"City"
]
==
"Beijing"
]
)
(
)
Inequality filtering
(
"City does not equal Beijing:"
)
(
df
[
df
[
"City"
]
!=
"Beijing"
]
)
(
)
Greater than and less than
(
"Salary greater than 12000:"
)
(
df
[
df
[
"Salary"
]
12000
]
)
(
)
String conditions
(
"Name contains 'three':"
)
(
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
(
"Beijing AND salary>10000:"
)
(
df
[
(
df
[
"City"
]
==
"Beijing"
)
&
(
df
[
"Salary"
]
10000
)
]
)
(
)
OR condition: use the | symbol
(
"Tech department OR salary>15000:"
)
(
df
[
(
df
[
"Department"
]
==
"Technology"
)
|
(
df
[
"Salary"
]
15000
)
]
)
(
)
NOT condition: use the ~ symbol
(
"Not the tech department:"
)
(
df
[
~
(
df
[
"Department"
]
==
"Technology"
)
]
)
(
)
Complex combinations
(
"(Beijing AND age>25) OR (Shanghai):"
)
(
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'sand、orThe 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
(
"City is Beijing or Shanghai:"
)
(
df
[
df
[
"City"
]
.
isin
(
[
"Beijing"
,
"Shanghai"
]
)
]
)
(
)
Not in a list
(
"City is neither Beijing nor Shanghai:"
)
(
df
[
~
df
[
"City"
]
.
isin
(
[
"Beijing"
,
"Shanghai"
]
)
]
)
(
)
isin on multiple columns
df2
=
pd.
DataFrame
(
{
"City"
:
[
"Beijing"
,
"Shanghai"
]
,
"Department"
:
[
"Technology"
,
"Sales"
]
}
)
(
"Satisfy both city and department:"
)
(
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
(
"Keep values greater than 3, set the others to 0:"
)
result
=
df.
where
(
df
3
,
0
)
(
result
)
(
)
Use another DataFrame as the condition
other
=
pd.
DataFrame
(
{
"A"
:
[
True
,
False
,
True
,
False
]
,
"B"
:
[
False
,
True
,
False
,
True
]
}
)
(
"Filter by a conditional DataFrame:"
)
(
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
(
"City contains 'Beijing':"
)
(
df
[
df
[
"City"
]
.
str
.
contains
(
"Beijing"
)
]
)
(
)
Start/End
(
"Email starts with zhang:"
)
(
df
[
df
[
"email"
]
.
str
.
startswith
(
"zhang"
)
]
)
(
)
Regex Matching
(
"Email username length greater than 4:"
)
(
df
[
df
[
"email"
]
.
str
.
extract
(
r
"(\w+)@"
)
[
0
]
.
str
.
len
(
)
4
]
)
(
)
Multiple Pattern Matching
(
"Cities starting with Bei, Shang, Guang, Shen:"
)
(
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
(
"Age between 25 and 30 (inclusive):"
)
(
df
[
df
[
"Age"
]
.
between
(
25
,
30
)
]
)
(
)
Quantile Filtering
q1
=
df
[
"Salary"
]
.
quantile
(
0.25
)
q3
=
df
[
"Salary"
]
.
quantile
(
0.75
)
(
f
"Salary between 25% and 75% ({q1}-{q3}):"
)
(
df
[
df
[
"Salary"
]
.
between
(
q1
,
q3
)
]
)
(
)
Smallest/Largest N Rows
(
"Top 3 highest salaries:"
)
(
df.
nlargest
(
3
,
"Salary"
)
)
(
)
(
"Bottom 2 lowest salaries:"
)
(
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"
)
(
"Time series data:"
)
(
df
)
(
)
Filter by Date
(
"Data for 2024-01-05:"
)
(
df.
loc
[
"2024-01-05"
]
)
(
)
Date Range Filtering
(
"2024-01-03 to 2024-01-07:"
)
(
df.
loc
[
"2024-01-03"
:
"2024-01-07"
]
)
(
)
Using truncate (a more efficient slicing method)
(
"truncate filtering:"
)
(
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
(
"Age>26 and City='Beijing':"
)
(
df.
query
(
"Age > 26 and City == 'Beijing'"
)
)
(
)
Using variables
min_age
=
26
city
=
"Beijing"
(
f
"Age>{min_age} and City={city}:"
)
(
df.
query
(
"Age > @min_age and City == @city"
)
)
(
)
Use backticks when column names contain spaces
df2
=
df.
rename
(
columns
=
{
"Name"
:
"Surname Name"
}
)
(
"When a column name contains spaces:"
)
(
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,
querythe method's syntax is closer to natural language, making the code more readable. When the data volume is large,loccombined with boolean arrays is usuallyqueryfaster.