You can use the following methods to filter the values in a pandas Series:
Method 1: Filter Values Based on One Condition
#filter for values equal to 7 my_series.loc[lambda x : x == 7]
Method 2: Filter Values Using “OR” Condition
#filter for values less than 10 or greater than 20 my_series.loc[lambda x : (x 20)]
Method 3: Filter Values Using “AND” Condition
#filter for values greater than 10 and less than 20 my_series.loc[lambda x : (x > 10) & (x
Method 4: Filter Values Contained in List
#filter for values that are equal to 4, 7, or 23 my_series[my_series.isin([4, 7, 23])]
This tutorial explains how to use each method in practice with the following pandas Series:
import pandas as pd
#create pandas Series
data = pd.Series([4, 7, 7, 12, 19, 23, 25, 30])
#view pandas Series
print(data)
0 4
1 7
2 7
3 12
4 19
5 23
6 25
7 30
dtype: int64
Example 1: Filter Values Based on One Condition
The following code shows how to filter the pandas Series for values equal to 7:
#filter for values equal to 7 data.loc[lambda x : x == 7] 1 7 2 7 dtype: int64
We can also filter for values not equal to 7:
#filter for values not equal to 7 data.loc[lambda x : x != 7] 0 4 3 12 4 19 5 23 6 25 7 30 dtype: int644
Example 2: Filter Values Using “OR” Condition
The following code shows how to filter the pandas Series for values less than 10 or greater than 20:
#filter for values less than 10 or greater than 20 data.loc[lambda x : (x 20)] 0 4 1 7 2 7 5 23 6 25 7 30 dtype: int64
Example 3: Filter Values Using “AND” Condition
The following code shows how to filter the pandas Series for values greater than 10 and less than 20:
#filter for values greater than 10 and less than 20 data.loc[lambda x : (x > 10) & (x
Example 4: Filter Values Contained in List
The following code shows how to filter the pandas Series for values that are contained in a list:
#filter for values that are equal to 4, 7, or 23 data[data.isin([4, 7, 23])] 0 4 1 7 2 7 5 23 dtype: int64
Additional Resources
The following tutorials explain how to perform other common filtering operations in Python:
How to Filter Pandas DataFrame Rows that Contain a Specific String
How to Filter a Pandas DataFrame on Multiple Conditions
How to Use “NOT IN” Filter in Pandas DataFrame