正規表現を使用すると、次のようになります。
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
問題を解決するにはどうすればいいでしょうか?
ありがとう。
ベストアンサー1
によるドキュメント、指定する必要がありますキャプチャグループ(つまり、括弧) はstr.extract
、抽出するためのものです。
Series.str.extract(pat, flags=0, expand=True)
シリーズ内の各対象文字列について、正規表現 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