How to extract sub string by defining before and after delimiter

Viewed 56

I have data frame which contains the URLs and I want to extract something in between.

df
    URL
    https://storage.com/vision/Glass2020/2020-02-04_B8I8FZHl-xJ_2236301468348443721.jpg
    https://storage.com/vision/Carpet5020/2020-02-04_B8I8FZHl-xJ_2236301468348443721.jpg
    https://storage.com/vision/Metal8020/2020-02-04_B8I8FZHl-xJ_2236301468348443721.jpg

desired output would be like this

            URL                                                                           Type
 https://storage.com/vision/Glass2020/2020-02-04_B8I8FZHl-xJ_2236301468348443721.jpg      Glass2020
 https://storage.com/vision/Carpet5020/2020-02-04_B8I8FZHl-xJ_2236301468348443721.jpg     Carpet5020
 https://storage.com/vision/Metal8020/2020-02-04_B8I8FZHl-xJ_2236301468348443721.jpg      Metal8020

I would use df['URL'].str.extract but to understand how to define before and after the delimiter.

2 Answers

One idea is use Series.str.split with select second last value by indexing:

df['Type'] = df['URL'].str.split('/').str[-2]
print (df)
                                                 URL        Type
0  https://storage.com/vision/Glass2020/2020-02-0...   Glass2020
1  https://storage.com/vision/Carpet5020/2020-02-...  Carpet5020
2  https://storage.com/vision/Metal8020/2020-02-0...   Metal8020

EDIT: For specify different values outside expected output use Series.str.extract:

df['Type'] = df['URL'].str.extract('vision/(.+)/2020')
print (df)
                                                 URL        Type
0  https://storage.com/vision/Glass2020/2020-02-0...   Glass2020
1  https://storage.com/vision/Carpet5020/2020-02-...  Carpet5020
2  https://storage.com/vision/Metal8020/2020-02-0...   Metal8020

Try str.split:

df['Type'] = df.URL.str.split('/').str[-2]
Related