Pandas: replace substring in string
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
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
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)