有没有一种计算效率更高的方法来使用 Pandas 找到与正则表达式匹配的第一个匹配项?

Is there a more computationally efficient way to find the first occurrence matching a regular expression using Pandas?

在Pandas中是否有计算效率更高的方法来获得下面的最终输出?我只想要第一次出现,findall然后得到列表的第0个元素似乎在计算上效率低下,如下所示:

Input:
s= pd.Series(["David Matt Juan Peter David James",
            "Scott David Peter Sam David Ron",
            "Dan Phil David Sam Pedro David Mani"])
s_find= s.str.findall(r'David [A-za-z]*')
print(s_find)

Output:
0    [David Matt, David James]
1     [David Peter, David Ron]
2      [David Sam, David Mani]

Input:
s_find= s_find.str[0]
print(s_find)

Output:
0     David Matt
1    David Peter
2      David Sam

您可以使用 str.extract 只取第一场比赛:

s.str.extract('(David [A-za-z]*)')

这个returns:

0     David Matt
1    David Peter
2      David Sam
dtype: object

或者,避免 pandas str 方法,您可以使用列表理解:

import re

pd.Series([re.search('(David [A-za-z]*)', i).group() for i in s.values])

0     David Matt
1    David Peter
2      David Sam
dtype: object