str.startswith 使用正则表达式

问题描述 投票:0回答:3

我可以理解为什么 str.startswith() 不处理正则表达式吗:

   col1
0  country
1  Country

i.e : df.col1.str.startswith('(C|c)ountry')

它返回所有值 False :

   col1
0  False
1  False
regex pandas series
3个回答
26
投票

Series.str.startswith
不接受正则表达式,因为它的行为类似于普通 Python 中的
str.startswith
,后者不接受正则表达式。另一种方法是使用正则表达式匹配(如文档中所述):

df.col1.str.contains('^[Cc]ountry')

字符类

[Cc]

 可能是匹配 
C
c
(C|c)
 更好的方法,当然除非您需要捕获使用哪个字母。在这种情况下,你可以这样做
([Cc])


8
投票

Series.str.startswith

 不接受正则表达式。使用 
Series.str.match
 代替:

df.col1.str.match(r'(C|c)ountry', as_indexer=True)

输出:

0 True 1 True Name: col1, dtype: bool
    

0
投票

Series.str.startswith

也可以接收这样的元组:

df.col1.str.startswith(("Country","country"))
现在搜索元组中的所有元素。您还可以在 

Series.str.startswith

 中将元组读取为 OR 运算符。

© www.soinside.com 2019 - 2024. All rights reserved.