2017-09-14 19 views
1

我有一個dataframedt 名和列名的listnn_language「ValueError異常:一個系列的真值不明確」的數據幀使用具有lambda表達式條件時

編輯:加入樣品數據

dt = pd.DataFrame({"language1": ["english", "english123", "ingles", "ingles123", "14.0", "13", "french"], 
        "language2": ["englesh", "english123", "ingles", "ingles123", "14", "13", "french"]}) 
nn_language = dt.columns[dt.columns.str.contains("language")] 

dt[nn_language]的所有元素都是object類型。 我想什麼做的,就是改變dt[nn_language]的初始值"english"如果初始值是like("english","ingles",14)否則我要初始值更改爲"other"

我曾嘗試:dt[nn_language].apply(lambda x: 'english' if x.str.contains('^engl|^ingl|14.0') else 'other')

但我得到一個錯誤ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().',

Thisthis沒有幫助我

回答

3

使用isin

check = ["english","ingles", '14'] 
dt[nn_language].apply(lambda x: np.where(x.isin(check) , 'english', 'other')) 

或者:

dt[nn_language].apply(lambda x: pd.Series(np.where(x.isin(check) , 'english', 'other'))) 

看來你需要:

dt[nn_language].apply(lambda x: np.where(x.str.contains('^engl|^ingl|14.0') , 'english', 'other')) 
+0

在你的答案,我認爲'14'缺少引號,因爲所有的元素的類型'object'的。所以我認爲它應該是'[「英語」,「ingles」,'14']'。除此之外,它的工作原理,我認爲你比@coldspeed快一點!快速跟進問題,你知道我的錯誤來自哪裏嗎? – quant

+0

@quant不,我是第一個。如果您必須決定通過時間接受哪個答案。 –

+0

我想你需要''14'如果字符串,或者'14'如果數字。或兩者。 – jezrael

1

你可以使用df.applynp.wherepd.Series.isin

dt[nn_language] = dt[nn_language].apply(lambda x:\ 
     np.where(x.isin(["english","ingles","14"]), 'english', 'other')) 

df 
     Col1 
0 english 
1  test 
2  14 
3  foo 
4 ingles 

nn_language = ['Col1'] 

df[nn_language] = df[nn_language].apply(lambda x: \ 
     np.where(x.isin(["english","ingles",'14']), 'english', 'other')) 
df 

    Col1 
0 english 
1 other 
2 english 
3 other 
4 english 
相關問題