Python Pandas Dataframe 条件 If、Elif、Else

标签 python if-statement pandas dataframe

在 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'] = '--'

所需输出示例:

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

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

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

最佳答案

这是一种方法,使用 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')

您可以将其分配给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        --

关于Python Pandas Dataframe 条件 If、Elif、Else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30649713/

相关文章:

python - 在 Python 中组合 except 和 else

python - 列表索引超出范围 : Importing info from two lists into one conditionally

python - 将 pandas 列从对象转换为字符串或 int/float 类型是否有必要或有益?

python - 如何修改ndarray矩阵中的特定字段

python - 如何使用 Windows 批处理文件获取 Python 位置?

python - SQL炼金术 : How to make an integer column auto_increment (and unique) without making it a primary key?

c++ - 有没有比使用 "if"更快/更短的方式在 C++ 中进行这些测试?

python - 从列表中更改 Pandas Dataframe 中的列名称

python - 如何使用 pymysql 将 mySQL 查询结果存储到 pandas DataFrame 中?

python - (TypeError : expected string or bytes-like object) when calling function in Django