Art Yudin
Art Yudin

Reputation: 17

pandas str.replace value of a column from another column

I am kinda lost here, I am trying to replace a part of the str within one column that is matching value from a separate column.

This is what i have so far

    brand       product           
0   BestBrand   prA by BestBrand    
1   newBrand    prB by newBrand 
2   GreatBrand  prC by GreatBrand

and I need something like this,

    brand       product             newProductName
0   BestBrand   prA by BestBrand    prA
1   newBrand    prB by newBrand     prB
2   GreatBrand  prC by GreatBrand   prC

Tried these methods,

h = new_file.brand
new_file['newProductName']=new_file.product.str.replace(h, '')

new_file.loc[new_file['newProductName'], 'product']= new_file.product.apply(lambda x: x.replace(h, '')) 

Upvotes: 1

Views: 1190

Answers (1)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

You can use apply and replace i.e

df['new'] = df.apply(lambda x : x['product'].replace(('by '+x['brand']),''),1)

     brand           product   new
0  BestBrand  prA by BestBrand  prA 
1  BestBrand  prB by BestBrand  prB 
2  BestBrand  prC by BestBrand  prC 

Upvotes: 1

Related Questions