pandas 熊猫:替换字符串中的子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38565849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: replace substring in string
提问by ldevyataykina
I want to replace substring icashier.alipay.com
in column in df
我想替换icashier.alipay.com
列中的子字符串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
.
到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
.
我尝试df['url'].replace('icashier.alipay.com', 'aliexpress.com', 'inplace=True')
但它返回empty dataframe
。
回答by jezrael
Use replace
with dict
for replacing and parameters inplace=True
and regex=True
:
使用replace
与dict
更换和参数inplace=True
和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
回答by EdChum
use str.replace
to replace a substring, replace
looks for exact matches unless you pass a regex pattern and param regex=True
:
用于str.replace
替换子字符串,replace
查找完全匹配,除非您传递正则表达式模式和参数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