【发布时间】:2015-06-05 01:03:38
【问题描述】:
在 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()?不需要.str部分
标签: python if-statement pandas dataframe