2016-10-02 70 views
5

我有兩列「A」和「B」一個大熊貓據幀「DF」申請,我有兩個參數大熊貓,與Args中的數據幀行條目

def myfunction(B, A): 
    # do something here to get the result 
    return result 

,我想一個函數應用它行通過行使用「應用」功能

df['C'] = df['B'].apply(myfunction, args=(df['A'],)) 

的df,但我得到的錯誤

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

最新發生在這裏,它似乎需要df ['A']作爲整個系列!而不僅僅是根據需要從該系列中輸入行。

回答

9

我想你需要:

import pandas as pd 
df = pd.DataFrame({'A':[1,2,3], 
        'B':[4,5,6]}) 

print (df) 
    A B 
0 1 4 
1 2 5 
2 3 6 

def myfunction(B, A): 
    #some staff 
    result = B + A 
    # do something here to get the result 
    return result 

df['C'] = df.apply(lambda x: myfunction(x.B, x.A), axis=1) 
print (df) 
    A B C 
0 1 4 5 
1 2 5 7 
2 3 6 9 

或者:

def myfunction(x): 

    result = x.B + x.A 
    # do something here to get the result 
    return result 

df['C'] = df.apply(myfunction, axis=1) 
print (df) 
    A B C 
0 1 4 5 
1 2 5 7 
2 3 6 9 
+0

爲什麼不能我使用的應用功能的 'ARGS' 的說法? –

+0

檢查[this](http://stackoverflow.com/a/12183507/2901002)。 – jezrael

+0

@RunnerBean你可以傳遞參數。 'apply'接受'kwargs',所以你可以傳遞這樣的參數:'df ['B']。apply(myfunction,A = df ['A'])'但是在這種情況下,將整個系列傳遞給每行應用的函數。 – piRSquared