在Pandas中有更高效的计算方法来获得下面的最终输出吗?我只想要第一次出现,并且看起来计算效率低,然后得到列表的第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