Pandas Series.str.contains


 

Series.str可用於以字符串形式訪問系列的值並對其應用幾種方法。Pandas Series.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返回。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM