微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐