2017-11-24 8 views
1

だから、私はパンダで次のようなDFを持っています以下のようになります。複数の条件は

Name  URL            Extract 
X   http://www.x.com/abc/xyz/url.html    abc 
X   http://www.x.com/yyz/hue/end.html    yyz 
Othername http://website.othername.com/abc.html   website 
Othername http://home.othername.com/someword/word.html  home 
Example  http://www.example.com/999/something/index.html 999 

ご覧のとおり、抽出したい部分はウェブサイトによって異なります。だから、 '名前'の下の値 'X'のために、私は1つの正規表現パターンを適用する必要があります。 'Othername'では、別のパターンです。

これには6種類の異なるパターンがあります。

私は「どこで」使ってみましたが、複数の条件を考慮していないウェブサイトのいずれかでのみ動作させることができました。次のように:

def ext(c): 
    if c['Name'] == 'X': 
     c.URL.str.extract(r'www\.x\.com\/(.*?)/') 
    elif c['Name'] == 'Example': 
     c.URL.str.extract(r'www\.example\.com\/(.*?)/') 
    (...) 
    else: 
     return '' 

df['Extract'] = df.apply(ext) 
df 

がどのように異なるstrのためにこの作業を行うことができ、私は「名前」の下にあります

df['Extract'] = np.where(df['Name'] == 'X', df.URL.str.extract(r'www\.x\.com\/(.*?)/'),'') 

を私はまた、このための関数を作成しようとしましたか?

答えて

1

これを試してみてください:

In [87]: df['Extract'] = (df.URL.replace([r'http[s]?://www\.[^/]*\/', r'http[s]?://'], ['',''], regex=True) 
    ...:     .str.extract(r'([^/.]*)', expand=False)) 
    ...: 

In [88]: df 
Out[88]: 
     Name            URL Extract 
0   X    http://www.x.com/abc/xyz/url.html  abc 
1   X    http://www.x.com/yyz/hue/end.html  yyz 
2 Othername   http://website.othername.com/abc.html website 
3 Othername  http://home.othername.com/someword/word.html  home 
4 Example http://www.example.com/999/something/index.html  999 
0

あなたは条件付き正規表現を使用することができます。これは、サブドメインはサブドメイン自体の他にwwwのときに/後の最初の部分を探していることを前提としてい

import re 
rx = re.compile(r'https?://(www)?(?(1)[^/+]+/([^/]+)|([^.]+))') 
def extract(col): 
    m = rx.match(col) 
    if m is not None: 
     return m.group(3) if m.group(3) is not None else m.group(2) 
    else: 
     return '' 

df['Extract'] = df['URL'].apply(extract) 

を。内訳


これは言う:

https?:// # match http:// or https.// 
(www)?  # capture www into group 1 if it is there 
(?(1)  # check if it was matched 
    [^/+]+/ # ... and if so fast forward ... 
    ([^/]+) # capture it into group 2 
|   # else 
    ([^.]+) # otherwise capture the part directly after http:// 
)   # into group 3 

a demo on regex101.comを参照してください。