The Series.str.contains() method is used to check whether each string value in a Pandas Series contains a given substring or pattern. It returns a Boolean Series (True/False) and is mainly used for filtering, searching, or flagging text data based on conditions.
This example checks whether each city name contains the substring "is".
import pandas as pd
s = pd.Series(['Paris', 'New York', 'Lisbon'])
print(s.str.contains('is'))
Output
0 True 1 False 2 True dtype: bool
Explanation:
- str.contains('is') checks each value for "is"
- Returns True where the substring is found
Syntax
Series.str.contains(pat, case=True, flags=0, na=None, regex=True)
Parameters:
- pat: Substring or regex pattern to search
- case: Case-sensitive match (True by default)
- flags: Regex flags (example: re.IGNORECASE)
- na: Value to use for missing data
- regex: Treat pat as regex if True
Returns: A Boolean Series or Index
Examples
Example 1: This example uses a regex pattern to find names where "i" is followed by a lowercase letter.
import pandas as pd
s = pd.Series(['Mike', 'Nick', 'Kim', 'John'])
r = s.str.contains('i[a-z]', regex=True)
print(r)
Output
0 True 1 True 2 True 3 False dtype: bool
Explanation: i[a-z] matches "ik" and "im" patterns in the strings
Example 2: This example performs a case-insensitive match to find "grape" in mixed-case text.
import pandas as pd
import re
s = pd.Series(['apple', 'GRAPE', 'banana'])
r = s.str.contains('grape', flags=re.IGNORECASE)
print(r)
Output
0 False 1 True 2 False dtype: bool
Explanation: flags=re.IGNORECASE allows matching "GRAPE" with "grape"
Example 3: This example shows how Series.str.contains() behaves when the Series contains missing values and how to handle them using the na parameter.
import pandas as pd
s = pd.Series(['Python', None, 'Pandas', 'NumPy'])
r = s.str.contains('Py', na=False)
print(r)
Output
0 True 1 False 2 False 3 True dtype: bool
Explanation:
- str.contains('Py') checks for "Py" in each string
- na=False ensures missing values (None) are treated as False instead of returning NaN