使用正则表达式时,我得到:

import re
string = r'http://www.example.com/abc.html'
result = re.search('^.*com', string).group()

在 Pandas 中,我写道:
df = pd.DataFrame(columns = ['index', 'url'])
df.loc[len(df), :] = [1, 'http://www.example.com/abc.html']
df.loc[len(df), :] = [2, 'http://www.hello.com/def.html']
df.str.extract('^.*com')

ValueError: pattern contains no capture groups

该如何解决呢?

谢谢。

最佳答案

根据docs,您需要为str.extract指定捕获组(即,括号)以提取。



每个捕获组在输出中构成其自己的列。

df.url.str.extract(r'(.*.com)')

                        0
0  http://www.example.com
1    http://www.hello.com
# If you need named capture groups,
df.url.str.extract(r'(?P<URL>.*.com)')

                      URL
0  http://www.example.com
1    http://www.hello.com

或者,如果您需要系列,
df.url.str.extract(r'(.*.com)', expand=False)

0    http://www.example.com
1      http://www.hello.com
Name: url, dtype: object

关于python - Pandas ValueError : pattern contains no capture groups,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54343378/

10-12 00:24
查看更多