Home > front end >  Assigning a string value in column x based off of a keyword in column y
Assigning a string value in column x based off of a keyword in column y

Time:07-11

I am trying to assign a brand name of a product to use on an excel doc. I have a column named "Name" which contains the name of multiple products, for example "12oz Rambler Bottle White", which I have a blank column named "Brand". I want to input the brand name, being "Yeti" in this case based off of just the word "Rambler", and so on for different products and brands. Right now I have to input the entire product name for over 200 products which I know there has to be a simpler way.

My current line of code for one product is df.loc[df['Name']=='12 Can Pelican Soft Cooler-Black', 'Brand'] = 'Pelican'

But I would like to make it where I can input an array of keywords from each product name and tie them to a single brand.

CodePudding user response:

You can try:

df.loc[df['Name'].str.contains(r'(?:keyword1|keyword2|keyword3)'), 'Brand'] = 'whatever'
  1. pandas.Series.str.contains() tests if pattern or regex is contained within a string of a Series
  2. You can provide as many keywords as desired, separated by |, within () to achieve logical or in regex. The ?: means you don't want groupping.
  • Related