Nick
Nick

Reputation: 247

How to replace text in Python pandas with certain criteria?

I have a column with websites that I want to replace all "https://" to "www." in my dataframe. For example, given the input:

https://stackoverflow.com
https://www.github.com

I run this:

data["columnname"]= data["columnname"].str.replace("https://", "www.", case = False) 

The output is:

www.stackoverflow.com
www.www.github.com

However the output should be:

www.stackoverflow.com
www.github.com

Is there a better way to write the code to not double the www. when replacing the https://?

Upvotes: 0

Views: 85

Answers (1)

David Erickson
David Erickson

Reputation: 16683

You can do a "double" replace and should first replace www. with an empty string to normalize the data and then replace https:// with www.:

data["columnname"]= data["columnname"].str.replace("www.", "", case = False).str.replace("https://", "www.", case = False)

Upvotes: 1

Related Questions