Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: replace substring in string

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.

like image 957
ldevyataykina Avatar asked Jul 25 '16 10:07

ldevyataykina


People also ask

How do I change substring in pandas?

You can replace substring of pandas DataFrame column by using DataFrame. replace() method. This method by default finds the exact sting match and replaces it with the specified value. Use regex=True to replace substring.

How do you replace a substring in Python?

Python String | replace() replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.

How do you replace a substring?

You can replace a substring using replace() method in Java. The String class provides the overloaded version of the replace() method, but you need to use the replace(CharSequence target, CharSequence replacement).

How do you replace words in pandas?

You can replace a string in the pandas DataFrame column by using replace(), str. replace() with lambda functions.


1 Answers

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
like image 135
jezrael Avatar answered Oct 02 '22 19:10

jezrael