Python Pandas Dataframe Conditional If, Elif, Else

末鹿安然 提交于 2020-07-19 07:14:36

问题


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:


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


来源:https://stackoverflow.com/questions/30649713/python-pandas-dataframe-conditional-if-elif-else

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!