2017-01-02 34 views
1

讓我們以一個例子與這個簡單的數據集:Lambda表達式語法錯誤與如果

example_set = pd.DataFrame(data = {"dirr":[1,0,-1,-1,1,-1,0], 
            "value": [125,130,80,8,150,251,18], 
            "result":[np.NaN for _ in range(7)]}) 

下面一行返回error:invalid syntax

example_set["result"].apply(lambda x : example_set["value"]if x["dirr"]==1) 

誰能告訴我什麼,我做錯了什麼? 請不要拿出解決方案,如何做到這一點沒有lambda:這只是一個超級簡化的例子,我彌補了我的問題。

+0

@EdChum請完整閱讀這個問題:*請不要拿出解決方案如何做到這一點沒有lambda表達式:這只是一個超級簡化的例子,我已經彌補了我的問題。* –

+0

'.apply(lambda x :example_set [「value」] if x [「dirr」] == 1 else x)'? – MYGz

+0

@MYGz這會返回另一個錯誤:'TypeError:'float'object is not subscriptable' –

回答

4

您需要包括在lambda語句else返回值:

In [7]: 
example_set['result'] = example_set.apply(lambda x: x['value'] if x['dirr'] == 1 else x['result'], axis = 1) 
example_set 

Out[7]: 
    dirr result value 
0  1 125.0 125 
1  0  NaN 130 
2 -1  NaN  80 
3 -1  NaN  8 
4  1 150.0 150 
5 -1  NaN 251 
6  0  NaN  18 

你嘗試:

example_set["result"].apply(lambda x : example_set["value"]if x["dirr"]==1) 

缺乏在本質上是else返回值,你也需要x['value']不是整個DF ,即使聲明被糾正,使用整個df也會產生一個奇怪的和不希望的返回結果:

In [14]: 
example_set.apply(lambda x: example_set['value'] if x['dirr'] == 1 else example_set['result'], axis = 1) 

Out[14]: 
     0  1  2 3  4  5  6 
0 125.0 130.0 80.0 8.0 150.0 251.0 18.0 
1 NaN NaN NaN NaN NaN NaN NaN 
2 NaN NaN NaN NaN NaN NaN NaN 
3 NaN NaN NaN NaN NaN NaN NaN 
4 125.0 130.0 80.0 8.0 150.0 251.0 18.0 
5 NaN NaN NaN NaN NaN NaN NaN 
6 NaN NaN NaN NaN NaN NaN NaN 
+0

此外,如果您在單個列上使用'.apply()',則無法訪問其他列的相應值。真正? – MYGz

+0

@MYGz是的,這是正確的,根據定義,它會調用沒有'axis'參數的'Series'版本,只有'DataFrame.apply'版本具有'axis'參數 – EdChum