在Python Pandas DataFrame
中,如果'搜索條件'列包含連接的管道分隔列表中的任何可能字符串,我試圖將特定標籤應用於行。我怎樣才能做到有條件if,elif,else與Pandas的陳述?Python熊貓數據框有條件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()
到語句的端部,但它的Brand
標籤適用於每一行。
我遇到的大多數例子都是比較列值==
是否等於(不是我想要的)或者正在執行數字比較,而不是文本字符串比較。
'.str.contains()'?不需要'.str'部分 – Zizouz212