2015-06-04 63 views
1

在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標籤適用於每一行。

我遇到的大多數例子都是比較列值==是否等於(不是我想要的)或者正在執行數字比較,而不是文本字符串比較。

+0

'.str.contains()'?不需要'.str'部分 – Zizouz212

回答

3

這裏有一個辦法做到這一點,利用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  -- 
+0

不錯!這對我來自Excel世界和嵌套的If語句有很大的意義。非常感謝。 – Jarad

+0

如何在沒有拋出SettingWithCopyWarning的情況下執行相同的任務? –