pandas.Series.str.contains#
- Series.str.contains(pat, case=True, flags=0, na=None, regex=True)[源代码]#
测试序列或索引的字符串中是否包含模式或正则表达式。
根据给定的模式或正则表达式是否包含在系列或索引的字符串中,返回布尔系列或索引。
- 参数
- pat应力
字符序列或正则表达式。
- case布尔值,默认为True
如果为True,则区分大小写。
- flagsInt,默认为0(无标志)
传递到re模块的标志,例如re.IGNORECASE。
- na标量,可选
为缺少的值填充值。默认设置取决于数组的数据类型。对于对象数据类型,
numpy.nan
使用的是。为StringDtype
,pandas.NA
是使用的。- regex布尔值,默认为True
如果为True,则假定PAT为正则表达式。
如果为False,则将PAT视为文字字符串。
- 退货
- 布尔值的序列或索引
布尔值的序列或索引,指示给定模式是否包含在序列或索引的每个元素的字符串中。
参见
match
类似,但更严格,依赖于re.Match而不是re.earch。
Series.str.startswith
测试每个字符串元素的开头是否与模式匹配。
Series.str.endswith
与以开头相同,但测试字符串的结尾。
示例
仅使用文字模式返回一系列布尔值。
>>> 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 。如果系列或索引不包含NaN值,则结果数据类型将为 bool ,否则,一个 object 数据类型。
>>> s1.str.contains('og', na=False, regex=True) 0 False 1 True 2 False 3 False 4 False dtype: bool
当字符串中出现这两个表达式中的任何一个时,返回‘house’或‘og’。
>>> s1.str.contains('house|dog', regex=True) 0 False 1 True 2 True 3 False 4 NaN dtype: object
使用忽略区分大小写 flags 使用正则表达式。
>>> 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
确保 pat 是一种非文字模式,当 regex 设置为True。注意:在下面的示例中,可能只需要 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