29

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.

3 Answers 3

48

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
Sign up to request clarification or add additional context in comments.

2 Comments

This appears only to work for a column, not for a dataframe. When I try this on a dataframe it no longer finds substrings.
For me this works for both columns and whole dataframes (without .str), for Pandas v2.2.2.
31

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

2 Comments

The .str fixed it for me with this one. if you commit .str then it does not replace substring in string
For me this is the opposite - it only works without .str, for Pandas v2.2.2, both for columns and whole dataframes.
2

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)

1 Comment

For the entire data frame, you can also use df.replace('icash...', 'aliex...', regex=True)

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.