2016-07-25 202 views
1

替換字符串我想在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 

更換子icashier.alipay.com在列aliexpress.com

慾望輸出

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

我嘗試df['url'].replace('icashier.alipay.com', 'aliexpress.com', 'inplace=True')但它返回empty dataframe

回答

5

使用replacedict更換和參數inplace=Trueregex=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 
2

使用str.replace更換子,replace查找精確匹配,除非你傳遞一個正則表達式模式和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 
+0

這不是一個就地操作;需要重新分配給'df ['url']' – Dmitri

+0

@Dmitri注意到,已經更新了答案,謝謝 – EdChum