1

I'm having a problem replacing a part of the string in Pandas.

I have a list of links of a website like this (for example):

https://stackoverflow.com/questions
https://stackoverflow.com/some_page
https://stackoverflow.com/about

and I would like to replace https://stackoverflow.com/ with link/.

And it should be like this:

link/questions
link/some_page
link/about

I tried something like this but it replaces the whole string:

df.loc[df['links'].str.contains('https://stackoverflow.com/'), 'links'] = 'link/'

links is the name of column

How do I do this?

Thanks in advance.

1
  • 2
    is it always https://stackoverflow.com/, or just for this example. If it is static, you can just replace it directly with str.replace Commented May 26, 2022 at 21:33

3 Answers 3

1

This should get you what you need as long as the URLs are consistent.

data = {
    'Column1' : ['https://stackoverflow.com/questions', 'https://stackoverflow.com/another', 'https://stackoverflow.com/last']
}

df = pd.DataFrame(data)
df['Column1'] = df['Column1'].apply(lambda x : 'Link/' + x.split('/')[-1])
df
Sign up to request clarification or add additional context in comments.

2 Comments

in case where the path has more slashes, i.e., additional paths, you can replace x.split('/')[3] with x.split('/')[-1] to pick the last part.
Your absolutely right! I'll update the code. I like that a lot better makes it more "fault proof" if only a little
1
df.loc[df['links'].str.contains('https://stackoverflow.com/'), 'links'] = \
    'link/' + df[0].str.extract('.*/(.*)') 

                                     0           links
0  https://stackoverflow.com/questions  link/questions
1  https://stackoverflow.com/some_page  link/some_page
2      https://stackoverflow.com/about      link/about

Comments

1

You need .str.replace in assignment

df.loc[df['links'].str.contains('https://stackoverflow.com/'), 'links'] = df['links'].str.replace('https://stackoverflow.com/', 'link/')
print(df)

                             links
0                   link/questions
1                   link/some_page
2                       link/about
3  https://stackoverflow/questions

Comments

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.