2017-04-04 70 views
1

我想比較數據框中的字符串與特定的警告,如果其中一個字符串已經等於「缺少」該值將被結轉。以elif方式比較熊貓數據框中的字符串

舉例來說,如果我的DF看起來像

df =pd.DataFrame({'Col1':['Dog','Cat','Missing'], 
     'Col2':['Dog', 'Monkey', 'Rat']}) 

。我問Col1中是col2的結果將是

True, False, Missing 

下面的代碼允許每行值的比較(我提供與「真」和「假」值),但我一直在努力與如何納入檢查「失蹤」

df['result'] = df.apply(lambda row: row[Col1] in row[Col2], axis=1) 

也許我應該放棄在這種情況下使用lambda函數的概念,並切換到IF/ELIF /聲明如在此僞代碼:

if df[df[Col1]] == "Missing": 
    df['result'] = 'Missing' 
elif df[df[Col1]] in df[df[Col2]]: 
    df['result'] = 'True' 
else: 
    df['result'] = 'False' 

我感謝所有幫助您可以提供。

回答

3

我想你可以使用雙numpy.where

mask1 = df['Col1'] == 'Missing' 
mask2 = df.apply(lambda row: row['Col1'] in row['Col2'], axis=1) 

df['result'] = np.where(mask1, 'Missing', 
       np.where(mask2, 'True', 'False')) 

print (df) 
     Col1 Col2 result 
0  Dog  Dog  True 
1  Cat Monkey False 
2 Missing  Rat Missing 
+0

燁說做到了,這是一個巧妙的方法!謝謝! – Dennis