pandas.Series.str.contains #
- 系列.str。包含( pat , case = True , flags = 0 , na = None , regex = True ) [来源] #
测试模式或正则表达式是否包含在系列或索引的字符串中。
根据给定模式或正则表达式是否包含在系列或索引的字符串中,返回布尔系列或索引。
- 参数:
- 帕特斯特
字符序列或正则表达式。
- case布尔值,默认 True
如果为 True,则区分大小写。
- flags int,默认0(无标志)
传递到 re 模块的标志,例如 re.IGNORECASE。
- na标量,可选
缺失值的填充值。默认值取决于数组的数据类型。对于对象数据类型,
numpy.nan
使用。对于StringDtype
,pandas.NA
使用。- 正则表达式bool,默认 True
如果为 True,则假定 pat 是正则表达式。
如果为 False,则将 pat 视为文字字符串。
- 返回:
- 布尔值的系列或索引
布尔值的系列或索引,指示给定模式是否包含在系列或索引的每个元素的字符串中。
也可以看看
match
类似,但更严格,依赖于 re.match 而不是 re.search。
Series.str.startswith
测试每个字符串元素的开头是否与模式匹配。
Series.str.endswith
与startswith相同,但测试字符串的结尾。
例子
仅使用文字模式返回一系列布尔值。
>>> s1 = pd.Series(['Mouse', 'dog', 'house and parrot', '23', np.nan]) >>> s1.str.contains('og', regex=False) 0 False 1 True 2 False 3 False 4 NaN dtype: object
仅使用文字模式返回布尔值索引。
>>> ind = pd.Index(['Mouse', 'dog', 'house and parrot', '23.0', np.nan]) >>> ind.str.contains('23', regex=False) Index([False, False, False, True, nan], dtype='object')
使用case指定区分大小写。
>>> s1.str.contains('oG', case=True, regex=True) 0 False 1 False 2 False 3 False 4 NaN dtype: object
将na指定为False而不是NaN会将 NaN 值替换为False。如果 Series 或 Index 不包含 NaN 值,则结果数据类型将为bool,否则为对象数据类型。
>>> s1.str.contains('og', na=False, regex=True) 0 False 1 True 2 False 3 False 4 False dtype: bool
当任一表达式出现在字符串中时,返回“house”或“dog”。
>>> s1.str.contains('house|dog', regex=True) 0 False 1 True 2 True 3 False 4 NaN dtype: object
使用带有正则表达式的标志忽略大小写。
>>> import re >>> s1.str.contains('PARROT', flags=re.IGNORECASE, regex=True) 0 False 1 False 2 True 3 False 4 NaN dtype: object
使用正则表达式返回任何数字。
>>> s1.str.contains('\\d', regex=True) 0 False 1 False 2 False 3 True 4 NaN dtype: object
当regex设置为 True时,确保pat不是文字模式。请注意,在以下示例中,人们可能期望只有s2[1]和s2[3]返回True。但是,“.0”作为正则表达式可匹配后跟 0 的任何字符。
>>> s2 = pd.Series(['40', '40.0', '41', '41.0', '35']) >>> s2.str.contains('.0', regex=True) 0 True 1 True 2 False 3 True 4 False dtype: bool