gpt4 book ai didi

python - Pandas 值错误 : pattern contains no capture groups

转载 作者:太空狗 更新时间:2023-10-30 00:34:06 26 4
gpt4 key购买 nike

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

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 指定一个捕获组(即括号),以便提取。

Series.str.extract(pat, flags=0, expand=True)
For each subject string in the Series, extract groups from the first match of regular expression pat.

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

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 值错误 : pattern contains no capture groups,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54343378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com