Pandas: replace substring in string

I want to replace substring icashier.alipay.com in column in df

url
icashier.alipay.com/catalog/2758186/detail.aspx
icashier.alipay.com/catalog/2758186/detail.aspx
icashier.alipay.com/catalog/2758186/detail.aspx
vk.com

to aliexpress.com.

Desire output

aliexpress.com/catalog/2758186/detail.aspx
aliexpress.com/catalog/2758186/detail.aspx
aliexpress.com/catalog/2758186/detail.aspx
vk.com

I try df['url'].replace('icashier.alipay.com', 'aliexpress.com', 'inplace=True') but it return empty dataframe.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use replace with dict for replacing and regex=True:

df['url'] = df['url'].replace({'icashier.alipay.com': 'aliexpress.com'}, regex=True)
print (df)
                                          url
0  aliexpress.com/catalog/2758186/detail.aspx
1  aliexpress.com/catalog/2758186/detail.aspx
2  aliexpress.com/catalog/2758186/detail.aspx
3                                      vk.com

Method 2

use str.replace to replace a substring, replace looks for exact matches unless you pass a regex pattern and param regex=True:

In [25]:
df['url'] = df['url'].str.replace('icashier.alipay.com', 'aliexpress.com')
df['url']

Out[25]:
0    aliexpress.com/catalog/2758186/detail.aspx
1    aliexpress.com/catalog/2758186/detail.aspx
2    aliexpress.com/catalog/2758186/detail.aspx
3                                        vk.com
Name: url, dtype: object

Method 3

In case someone (like me) needs to replace substring in whole DataFrame:

df = df.apply(lambda col: col.str.replace('icash...', 'aliex...'))

or just in defined columns (and all others remain unchanged):

cols = ['a', 'c'] # list of all columns with value to replace
df = df.apply(lambda col: col.str.replace('icash...', 'aliex...') if col.name in cols else col)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x