Pandas Series.str.contains() Function
Series.str.contains() is a Pandas function used to check whether a string contains a specified substring.
In data processing, we often need to filter by text content, such as finding records containing specific keywords or filtering out text that matches a certain pattern.contains() The function can check whether each string element contains a specified substring or regular expression pattern.
Word meaning:contains means "contains", indicating a check for whether a string contains the specified content.
Basic syntax and parameters
str.contains() is a string accessor method of Series, so you need a Series containing strings first, and then call it through the .str accessor.
Syntax format
Series.str.contains(pat, case=True, regex=True, na=None)
Parameter Description
| Parameters | Type | Required | Description | Default value |
|---|---|---|---|---|
| pat | str | Required | The pattern to search for; it can be a plain string or a regular expression. | - |
| case | bool | Optional | Whether to be case-sensitive. Defaults to True (case-sensitive). | True |
| regex | bool | Optional | Whether to treat the pat parameter as a regular expression. Defaults to True. | True |
| na | object | Optional | The value to return when an element is NaN. Defaults to None (returns NaN). | None |
Function description
- Return Value: Returns a boolean Series indicating whether each element contains the specified pattern.
- effect: Checks each string element in the Series, returning True or False.
- Note: Uses regular expression matching by default, allowing more complex patterns to be matched.
Example
Let us thoroughly master str.contains() through a series of examples from simple to complex.
Example 1: Basic Usage - Checking Whether a Substring Is Contained
Example
import
pandas
as
pd
Create a Series containing text
s
=
pd.
Series
(
[
'apple'
,
'banana'
,
'grape'
,
'pineapple'
,
'orange'
]
)
Check whether 'ap' is contained
result
=
s.
str
.
contains
(
'ap'
)
(
"Original Series:"
)
(
s
)
(
"nContains 'ap':"
)
(
result
)
Output result:
原始 Series:
0 apple
1 banana
2 grape
3 pineapple
4 orange
dtype: object
是否包含 'ap':
0 True
1 False
2 True
3 True
4 False
Code analysis:
s.str.contains('ap')Check whether each string contains the substring 'ap'.- 'apple' contains 'ap', so True is returned.
- 'banana' does not contain 'ap', so False is returned.
- 'grape' contains 'ap', so True is returned.
- 'pineapple' contains 'ap', so True is returned.
Example 2: Matching Using Regular Expressions
contains() Regular expressions are used by default, allowing more complex patterns to be matched.
Example
import
pandas
as
pd
Create a Series containing text
s
=
pd.
Series
(
[
'hello123'
,
'world456'
,
'runoob789'
,
'python'
,
'test123'
]
)
Use a regular expression to match strings that start with a letter followed by digits
result
=
s.
str
.
contains
(
r
'^[a-zA-Z]+d+$'
)
(
"Original Series:"
)
(
s
)
(
"nMatch Pattern Starting with a Letter and Ending with a Digit:"
)
(
result
)
Output result:
原始 Series:
0 hello123
1 world456
2 runoob789
3 python
4 test123
dtype: object
Pattern matching letters at the beginning and numbers at the end:
0 True
1 True
2 True
3 False
4 True
Code analysis:
r'^[a-zA-Z]+d+$'is a regular expression that matches strings starting with a letter and ending with a digit.^indicates the start of a string,$indicates the end of a string.- 'python' contains no digits, so it does not match.
Example 3: Case-Insensitive Matching
By setting case=False Case-insensitive matching can be achieved.
Example
import
pandas
as
pd
Create a Series containing text with different cases
s
=
pd.
Series
(
[
'Apple'
,
'APPLE'
,
'apple'
,
'Banana'
,
'APPLE'
]
)
Case-sensitive matching
result_case
=
s.
str
.
contains
(
'APPLE'
)
Case-insensitive matching
result_nocase
=
s.
str
.
contains
(
'APPLE'
,
case
=
False
)
(
"Original Series:"
)
(
s
)
(
"nCase-Sensitive Match for 'APPLE':"
)
(
result_case
)
(
"nCase-Insensitive Match for 'APPLE':"
)
(
result_nocase
)
Output result:
原始 Series:
0 Apple
1 APPLE
2 apple
3 Banana
4 APPLE
dtype: object
区分大小写匹配 'APPLE':
0 False
1 True
2 False
3 False
4 True
不区分大小写匹配 'APPLE':
0 True
1 True
2 True
3 False
4 True
Code analysis:
case=True(the default) is case-sensitive and matches only the exact string 'APPLE'.case=FalseWith case-insensitive matching, 'Apple', 'APPLE', and 'apple' all match.
Example 4: Handling missing values
Pass na The parameter specifies how NaN values are handled.
Example
import
pandas
as
pd
import
numpy
as
np
Create a Series containing NaN values
s
=
pd.
Series
(
[
'apple'
,
'banana'
,
np.
nan
,
'grape'
,
None
]
)
Default handling of NaN (returns NaN)
result_default
=
s.
str
.
contains
(
'ap'
)
Return False when NaN is specified
result_na_false
=
s.
str
.
contains
(
'ap'
,
na
=
False
)
(
"Original Series:"
)
(
s
)
(
"nDefault Handling (Returns NaN):"
)
(
result_default
)
(
"nTreat NaN as False:"
)
(
result_na_false
)
Output result:
原始 Series:
0 apple
1 banana
2 NaN
3 grape
4 None
dtype: object
默认处理(返回 NaN):
0 True
1 False
2 NaN
3 True
4 NaN
将 NaN 视为 False:
0 True
1 False
2 False
3 True
4 False
Code analysis:
- By default, NaN and None return NaN.
- Settings
na=FalseNaN can be treated as a non-match. - In real data processing, this is useful because it avoids filtering problems caused by NaN.
Example 5: Filtering Data
contains() Often used in combination with boolean indexing to filter data.
Example
import
pandas
as
pd
Create a Series with mock product data
products
=
pd.
Series
(
[
'iPhone 14 Pro'
,
'Samsung Galaxy S23'
,
'iPhone 13'
,
'Google Pixel 7'
,
'iPad Pro'
,
'MacBook Air'
,
'Dell XPS 15'
]
)
Filter products containing 'iPhone'
iphone_products
=
products
[
products.
str
.
contains
(
'iPhone'
)
]
Filter products not containing 'i' (case-sensitive)
no_i_products
=
products
[
~
products.
str
.
contains
(
'i'
)
]
(
"All products:"
)
(
products
)
(
"nProducts containing 'iPhone':"
)
(
iphone_products
)
(
"nProducts not containing uppercase 'I':"
)
(
no_i_products
)
Output result:
All products:
0 iPhone 14 Pro
1 Samsung Galaxy S23
2 iPhone 13
3 Google Pixel 7
4 iPad Pro
5 MacBook Air
6 Dell XPS 15
dtype: object
Products containing 'iPhone':
0 iPhone 14 Pro
2 iPhone 13
dtype: object
Products that do not contain uppercase 'I':
6 Dell XPS 15
Code analysis:
products[products.str.contains('iPhone')]Filters out products containing 'iPhone'.~products.str.contains('i')Use~Negated to filter out products not containing 'i'.- This is a common data filtering operation.
Notes
str.contains()Regular expressions are used by default (regex=True)。- If you need to match a plain string (not as a regular expression), you can set
regex=False。 - Case-sensitive by default; use
case=Falseto make it case-insensitive. - By default, NaN values return NaN; use
naparameter to specify the return value. - This function returns a boolean Series that can be used directly for boolean indexing to filter data.
Common Pandas functions