我有以下代码:
import pandas as pd
s = pd.Series(['toy story (1995)', 'the pirates (2014)'])
print(s.str.extract('.*\((.*)\).*',expand = True))
输出:
0
0 1995
1 2014
据我所知,提取函数正在拉取两个系列对象的括号之间的值。但是我不明白怎么做。 '.*\((.*)\).*'
究竟是什么意思?我认为星号表示外卡字符,但除此之外,我对这个表达式实际发生的事情感到很困惑。
.*\(
匹配一切直到第一个(
\).*
匹配从)
到结束的所有内容
(.*)
返回前两场比赛之间的所有内容
.* Match any number of characters
\( Match one opening parenthesis
(.*) Match any number of characters into the first capturing group
\) Match a closing parenthesis
.* Match any number of characters
这种表示法称为正则表达式,我猜Pandas在extract
函数中使用正则表达式,因此您可以获得更精确的数据。捕获组内的内容将被返回。
您可以在Wikipedia page上了解有关正则表达式的更多信息。
这是使用正则表达式的a test example。