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

Pandas Series.str.contains() Function

Pandas Series.str.contains() Function

Pandas Common Functions Common Pandas functions


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


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'

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nContains 'ap':"

)

print

(

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:

  1. s.str.contains('ap') Check whether each string contains the substring 'ap'.
  2. 'apple' contains 'ap', so True is returned.
  3. 'banana' does not contain 'ap', so False is returned.
  4. 'grape' contains 'ap', so True is returned.
  5. '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+$'

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nMatch Pattern Starting with a Letter and Ending with a Digit:"

)

print

(

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:

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

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nCase-Sensitive Match for 'APPLE':"

)

print

(

result_case

)

print

(

"nCase-Insensitive Match for 'APPLE':"

)

print

(

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:

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

)

print

(

"Original Series:"

)

print

(

s

)

print

(

"nDefault Handling (Returns NaN):"

)

print

(

result_default

)

print

(

"nTreat NaN as False:"

)

print

(

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:

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'

)

]

print

(

"All products:"

)

print

(

products

)

print

(

"nProducts containing 'iPhone':"

)

print

(

iphone_products

)

print

(

"nProducts not containing uppercase 'I':"

)

print

(

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:


Notes


Pandas Common Functions Common Pandas functions