简体   繁体   中英

Python Pandas Dataframe Conditional If, Elif, Else

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM