Pandas Series.str.contains() 方法



Pandas 中的 Series.str.contains() 方法用於測試 Series 或 Index 字串中是否包含模式或正則表示式。此方法會根據字串中是否存在給定的模式返回布林 Series 或 Index。

此方法可用於篩選和識別與特定模式匹配的字串,該模式可以是文字字串或正則表示式。

語法

以下是 Pandas Series.str.contains() 方法的語法 −

Series.str.contains(pat, case=True, flags=0, na=None, regex=True)

引數

Series.str.contains() 方法接受以下引數 −

  • pat − 要搜尋的字元序列或正則表示式。

  • case − 布林值,指示搜尋是否應區分大小寫。預設為 True。

  • flags − re 模組的正則表示式的標誌的整數值。預設為 0(無標誌)。

  • na − 用於填充缺失值的標量值。對於 object dtype,預設為 numpy.nan,對於 StringDtype,預設為 pandas.NA。

  • regex − 布林值,指示模式是否應視為正則表示式。預設為 True。

返回值

Series.str.contains() 方法返回一個布林值 Series 或 Index,指示給定的模式是否存在於 Series 或 Index 的每個字串元素中。

示例 1

此示例透過檢查字串“og”是否存在於 Series 的每個元素中,演示了 Series.str.contains() 方法的基本用法。

import pandas as pd
import numpy as np

# Create a Series of strings
s1 = pd.Series(['panda', 'dog', 'house and python', '23', np.nan])

# Check if 'og' is present in each string (literal match, not regex)
result = s1.str.contains('og', regex=False)

print("Input Series:")
print(s1)
print("\nSeries after calling str.contains('og', regex=False):")
print(result)

執行上述程式碼後,會產生以下輸出 −

Input Series:
0               panda
1                 dog
2    house and python
3                  23
4                 NaN
dtype: object

Series after calling str.contains('og', regex=False):
0    False
1     True
2    False
3    False
4      NaN
dtype: object

示例 2

以下是另一個示例,演示瞭如何使用Series.str.contains()方法來識別 Index 中包含子字串“26”的字串。

import pandas as pd
import numpy as np

# Create a series 
s= pd.Series([1, 2, 3, 4, 5], index=['panda', 'dog', 'house and python', '26.0', np.nan])

# Check if '26' is present in each string (literal match, not regex)
result = s.index.str.contains('26', regex=False)

print("Input Series:")
print(s)
print("\nIndex after calling str.contains('23', regex=False):")
print(result)

以下是有關上述程式碼的輸出 −

Input Series:
panda               1
dog                 2
house and python    3
26.0                4
NaN                 5
dtype: int64

Index after calling str.contains('23', regex=False):
Index([False, False, False, True, nan], dtype='object')

示例 3

在此示例中,我們使用正則表示式應用 Series.str.contains() 方法來匹配包含“house”或“dog”的任何字串。

import pandas as pd
import numpy as np

# Create a Series of strings
s1 = pd.Series(['panda', 'dog', 'house and python', '23', np.nan])

# Check if 'house' or 'dog' is present in each string (regex match)
result = s1.str.contains('house|dog', regex=True)

print("Input Series:")
print(s1)
print("\nSeries after calling str.contains('house|dog', regex=True):")
print(result)

以上程式碼的輸出如下 −

Input Series:
0               panda
1                 dog
2    house and python
3                  23
4                 NaN
dtype: object

Series after calling str.contains('house|dog', regex=True):
0    False
1     True
2     True
3    False
4      NaN
dtype: object
python_pandas_working_with_text_data.htm
廣告