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返回。

posted @ 2020-10-25 20:55  DaisyLinux  阅读(796)  评论(0编辑  收藏  举报