Pandas:替换string中的substring

时间:2016-07-25 10:54:02

标签: python pandas replace dataframe substring

我想替换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

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

3 个答案:

答案 0 :(得分:9)

使用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

答案 1 :(得分:6)

使用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

答案 2 :(得分:1)

如果有人(像我一样)需要替换整个 DataFrame 中的 substring

df = df.apply(lambda col: col.str.replace('icash...', 'aliex...'))

或者只是在定义的列中(并且所有其他保持不变):

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)