2

In a Python Pandas DataFrame, I'm trying to apply a specific label to a row if a 'Search terms' column contains any possible strings from a joined, pipe-delimited list. How can I do conditional if, elif, else statements with Pandas?

For example:

df = pd.DataFrame({'Search term': pd.Series(['awesomebrand inc', 'guy boots', 'ectoplasm'])})

brand_terms = ['awesomebrand', 'awesome brand']
footwear_terms = ['shoes', 'boots', 'sandals']

#Note: this does not work
if df['Search term'].str.contains('|'.join(brand_terms)):
  df['Label'] = 'Brand'
elif df['Search term'].str.contains('|'.join(footwear_terms)):
  df['Label'] = 'Footwear'
else:
  df['Label'] = '--'

Example desired output:

Search Term          Label
awesomebrand inc     Brand
guy boots            Footwear
ectoplasm            --

I've tried appending .any() to the ends of the contains() statements but it applies the Brand label to every row.

Most of the examples I come across are comparing if a column value == is equal to (not what I want) or are performing numeric comparisons, not text string comparisons.

1
  • .str.contains()? No need for the .str part Commented Jun 4, 2015 at 16:53

1 Answer 1

5

Here's one way to do it, using str.contains() and np.where()

In [26]:
np.where(df['Search term'].str.contains('|'.join(brand_terms)),
        'Brand',
         np.where(df['Search term'].str.contains('|'.join(footwear_terms)),
             'Footwear',
             '--'))

Out[26]:
array(['Brand', 'Footwear', '--'],
      dtype='|S8')

Which you can assign to df['Label'] like

In [27]: df['Label'] = np.where(df['Search term'].str.contains('|'.join(brand_terms)),
   ....:               'Brand',
   ....:               np.where(df['Search term'].str.contains('|'.join(footwear_terms)),
   ....:                       'Footwear',
   ....:                       '--'))

In [28]: df
Out[28]:
        Search term     Label
0  awesomebrand inc     Brand
1         guy boots  Footwear
2         ectoplasm        --
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! This makes a lot of sense to me coming from the world of Excel and nested If statements. Thanks a lot.
how do you go about the same task without having SettingWithCopyWarning thrown out?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.