在 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]*)')
返回:
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
