熊猫ValueError:模式不包含捕获组

时间:2019-01-24 09:35:08

标签: python pandas

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

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

我在大熊猫中写道:

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

如何解决问题?

谢谢。

3 个答案:

答案 0 :(得分:5)

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

  

Series.str.extract(pat, flags=0, expand=True)
  对于每个主题   系列中的字符串,从常规的第一个匹配项中提取组   表达方式。

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

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

答案 1 :(得分:2)

您需要为匹配组指定列url()

df['new'] = df['url'].str.extract(r'(^.*com)')
print (df)
  index                              url                     new
0     1  http://www.example.com/abc.html  http://www.example.com
1     2    http://www.hello.com/def.html    http://www.hello.com

答案 2 :(得分:2)

尝试使用此python库,可以很好地实现此目的:

使用urllib.parse

from urllib.parse import urlparse
df['domain']=df.url.apply(lambda x:urlparse(x).netloc)
print(df)

  index                              url           domain
0     1  http://www.example.com/abc.html  www.example.com
1     2    http://www.hello.com/def.html    www.hello.com
相关问题