Python| Pandas Series.str.contains()
Series.str 可用于以字符串形式访问系列的值并对其应用多种方法。 Pandas Series.str.contains()函数用于测试模式或正则表达式是否包含在系列或索引的字符串中。该函数根据给定模式或正则表达式是否包含在系列或索引的字符串中返回布尔系列或索引。
Syntax: Series.str.contains(pat, case=True, flags=0, na=nan, regex=True)
Parameter :
pat : Character sequence or regular expression.
case : If True, case sensitive.
flags : Flags to pass through to the re module, e.g. re.IGNORECASE.
na : Fill value for missing values.
regex : If True, assumes the pat is a regular expression.
Returns : Series or Index of boolean values
示例 #1:使用 Series.str.contains ()函数来查找模式是否存在于给定系列对象的基础数据字符串中。
Python3
# 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)
Python3
# find if 'is' substring is present
result = sr.str.contains(pat = 'is')
# print the result
print(result)
Python3
# 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)
Python3
# 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)
输出 :
现在我们将使用 Series.str.contains ()函数来查找模式是否包含在给定系列对象的基础数据中存在的字符串中。
Python3
# find if 'is' substring is present
result = sr.str.contains(pat = 'is')
# print the result
print(result)
输出 :
正如我们在输出中看到的,Series.str.contains()函数返回了一个布尔值的系列对象。如果传递的模式存在于字符串中,则为 true,否则返回 False。
示例 #2:使用 Series.str.contains ()函数来查找模式是否存在于给定系列对象的基础数据字符串中。使用正则表达式在字符串中查找模式。
Python3
# 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 ()函数来查找模式是否包含在给定系列对象的基础数据中存在的字符串中。
Python3
# 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)
输出 :
正如我们在输出中看到的,Series.str.contains()函数返回了一个布尔值的系列对象。如果传递的模式存在于字符串中,则为 true,否则返回 False。