Python Pandas Series.str.contains()

Python Pandas Series.str.contains()

Series.str可以用来将系列的值作为字符串访问,并对其应用几种方法。Pandas Series.str.contains()函数用于测试模式或词组是否包含在一个系列或索引的字符串中。该函数根据给定的模式或regex是否包含在系列或索引的字符串中,返回布尔系列或索引。

语法:

Series.str.contains(pat, case=True, flags=0, na=nan, regex=True)
Python

参数:
pat :字符序列或正则表达式。
case : 如果为真,则区分大小写。
flags : 用于传递给re模块的标志,例如re.IGNORECASE。
na :填补缺失的数值。
regex : 如果为真,假定pat是一个正则表达式。
返回:系列或布尔值的索引

示例#1:使用Series.str.contains a ()函数来查找给定系列对象中底层数据的字符串中是否存在一个模式。

# 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)
Python

输出 :

Python Pandas Series.str.contains()

现在我们将使用Series.str.contains a ()函数来查找在给定系列对象的底层数据中是否包含一个模式。

# find if 'is' substring is present
result = sr.str.contains(pat = 'is')
 
# print the result
print(result)
Python

输出 :

Python Pandas Series.str.contains()

正如我们在输出中看到的,Series.str.contains()函数返回了一个布尔值的系列对象。如果通过的模式存在于字符串中,则为真,否则返回假。
示例#2:使用Series.str.contains a ()函数来查找给定系列对象中底层数据的字符串中是否存在一个模式。使用正则表达式来查找字符串中的模式。

# 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)
Python

输出 :

Python Pandas Series.str.contains()

现在我们将使用Series.str.contains a ()函数来查找在给定系列对象的底层数据中是否包含一个模式。

# find if there is a substring such that it has
# the letter 'i' followed by any small alphabet.
result = sr.str.contains(pat = 'i[a-z]', regex = True)
 
# print the result
print(result)
Python

输出 :

Python Pandas Series.str.contains()

正如我们在输出中看到的,Series.str.contains()函数返回了一个布尔值的系列对象。如果通过的模式存在于字符串中,则为真,否则返回假。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册