Pandas: replace substring in string

2019-01-15 21:34发布

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.

2条回答
再贱就再见
2楼-- · 2019-01-15 21:56

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
查看更多
疯言疯语
3楼-- · 2019-01-15 22:18

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
查看更多
登录 后发表回答