【问题标题】:pandas ValueError: pattern contains no capture groupspandas ValueError:模式不包含捕获组
【发布时间】:2019-01-24 09:35:07
【问题描述】:

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

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

如何解决问题?

谢谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    根据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
    

    【讨论】:

      【解决方案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
      

      【讨论】:

        【解决方案3】:

        试试这个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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-06-20
          • 1970-01-01
          • 2020-04-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-23
          相关资源
          最近更新 更多