ldevyataykina ldevyataykina - 4 months ago 20
Python Question

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
.

Answer

Use replace with dict for replacing and parameters inplace=True and regex=True:

df['url'].replace({'icashier.alipay.com': 'aliexpress.com'}, inplace=True, 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