ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Pandas Series.str.contains

2020-10-25 21:01:30  阅读:151  来源: 互联网

标签:Series contains str sr 字符串 True Pandas


 

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

标签:Series,contains,str,sr,字符串,True,Pandas
来源: https://www.cnblogs.com/a00ium/p/13875151.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有