Python Pandas Dataframe 条件 If、Elif、Else

Jar*_*rad 2 python if-statement dataframe pandas

在 Python Pandas 中DataFrame,如果“搜索词”列包含来自连接的管道分隔列表中的任何可能的字符串,我将尝试将特定标签应用于行。如何使用 Pandas 执行条件 if、elif、else 语句?

例如:

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'] = '--'
Run Code Online (Sandbox Code Playgroud)

所需输出示例:

Search Term          Label
awesomebrand inc     Brand
guy boots            Footwear
ectoplasm            --
Run Code Online (Sandbox Code Playgroud)

我尝试附加.any()到语句的末尾contains(),但它将Brand标签应用到每一行。

我遇到的大多数示例都是比较列值是否==等于(不是我想要的)或正在执行数字比较,而不是文本字符串比较。

Zer*_*ero 5

这是一种方法,使用str.contains()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')
Run Code Online (Sandbox Code Playgroud)

您可以分配给df['Label']喜欢的

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        --
Run Code Online (Sandbox Code Playgroud)