在Python PandasDataFrame
中,如果“searchterms”列包含来自联接的、管道分隔的列表的任何可能的字符串,我将尝试对行应用特定的标签。我怎么能用熊猫做条件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'] = '--'
期望输出示例:
^{pr2}$我尝试过在contains()
语句的末尾追加.any()
,但它将Brand
标签应用到每一行。在
我遇到的大多数例子都是比较列值==
是否等于(不是我想要的)或者执行数值比较,而不是文本字符串比较。在
这里有一种方法,使用
str.contains()
和np.where()
您可以将其分配给
^{pr2}$df['Label']
,就像相关问题 更多 >
编程相关推荐