2

I have a Python Pandas data frame like following:

Id      Title            URL                                       PosterPath
Id-1    Bruce Almighty   https://www.youtube.com/embed/5VGyTOGxyVA  https://i.ytimg.com/vi/XXXRRR/hqdefault.jpg
Id-2    Superhero Movie  https://www.youtube.com/embed/3BnXz-7-y-o  https://i.ytimg.com/vi/XXXRRR/hqdefault.jpg
Id-3    Taken            https://www.youtube.com/embed/vjbfiOERDYs  https://i.ytimg.com/vi/XXXRRR/hqdefault.jpg

I want to replace sub-string "XXXRRR" from column PosterPath with sub-string which comes after the string "embed/" from the column "URL" Output data frame would look like following:

Id      Title            URL                                       PosterPath
Id-1    Bruce Almighty   https://www.youtube.com/embed/5VGyTOGxyVA  https://i.ytimg.com/vi/5VGyTOGxyVA/hqdefault.jpg
Id-2    Superhero Movie  https://www.youtube.com/embed/3BnXz-7-y-o  https://i.ytimg.com/vi/3BnXz-7-y-o/hqdefault.jpg
Id-3    Taken            https://www.youtube.com/embed/vjbfiOERDYs  https://i.ytimg.com/vi/vjbfiOERDYs/hqdefault.jpg

1 Answer 1

5

Use str.extract with Series.replace:

a = df['URL'].str.extract('embed/(.*)$', expand=False)
print (a)
0    5VGyTOGxyVA
1    3BnXz-7-y-o
2    vjbfiOERDYs
Name: URL, dtype: object

df['PosterPath'] = df['PosterPath'].replace('XXXRRR', a, regex=True)
print (df)
     Id            Title                                        URL  \
0  Id-1   Bruce Almighty  https://www.youtube.com/embed/5VGyTOGxyVA   
1  Id-2  Superhero Movie  https://www.youtube.com/embed/3BnXz-7-y-o   
2  Id-3            Taken  https://www.youtube.com/embed/vjbfiOERDYs   

                                         PosterPath  
0  https://i.ytimg.com/vi/5VGyTOGxyVA/hqdefault.jpg  
1  https://i.ytimg.com/vi/3BnXz-7-y-o/hqdefault.jpg  
2  https://i.ytimg.com/vi/vjbfiOERDYs/hqdefault.jpg  
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome answer!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.