Pandas Series.str.contains
阿新 • • 發佈:2020-10-25
Series.str
可用於以字串形式訪問系列的值並對其應用幾種方法。PandasSeries.str.contains()
函式用於測試序列或索引的字串中是否包含模式或正則表示式。函式根據給定的模式或正則表示式是否包含在Series或Index的字串中,返回boolean Series或Index。
語法:Series.str.contains(pat,case = True,flags = 0,na = nan,regex = True)
引數:
pat:字元序列或正則表示式。
case:如果為True,則區分大小寫。
flags:傳遞給re模組的標誌,例如re.IGNORECASE。
na:填充缺失值的值。
regex:如果為True,則假定pat是一個正則表示式。返回:布林值的序列或索引
示例1:使用Series.str.contains()
函式查詢給定系列物件中基礎資料的字串中是否存在模式。
# importing pandas as pd import pandas as pd # importing re for regular expressions import re # Creating the Series sr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich']) # Creating the index idx= ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # set the index sr.index = idx # Print the series print(sr)
輸出:
現在,我們將使用Series.str.contains()
函式查詢給定系列物件的基礎資料中存在的字串中是否包含模式。
# find if 'is' substring is present result = sr.str.contains(pat = 'is') # print the result print(result)
正如我們在輸出中看到的那樣,該Series.str.contains()
函式返回了一系列布林值的物件。這是True
如果傳遞的模式存在其他字串中False
返回。
Example#2:使用Series.str.contains()
函式查詢給定系列物件中基礎資料的字串中是否存在模式。使用正則表示式在字串中查詢模式。
# importing pandas as pd import pandas as pd # importing re for regular expressions import re # Creating the Series sr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney']) # Creating the index idx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5'] # set the index sr.index = idx # Print the series print(sr)
現在,我們將使用Series.str.contains()
函式查詢給定系列物件的基礎資料中存在的字串中是否包含模式。
# find if there is a substring such that it has # the letter 'i' follwed by any small alphabet. result = sr.str.contains(pat = 'i[a-z]', regex = True) # print the result print(result)
正如我們在輸出中看到的那樣,該Series.str.contains()
函式返回了一系列布林值的物件。這是True
如果傳遞的模式存在其他字串中False
返回。