Pandas, apply to args, which are dataframe string strings

I have a pandas dataframe 'df' with two columns 'A' and 'B', I have a function with two arguments

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

and I would like to apply it line by line to df using the "apply" function

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

but i get an error

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

What happens here, it seems that df ['A'] is like a whole series! not just a row entry from this series, if required.

+5
source share
1 answer

I think you need:

 import pandas as pd df = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]}) print (df) AB 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(xB, xA), axis=1) print (df) ABC 0 1 4 5 1 2 5 7 2 3 6 9 

Or:

 def myfunction(x): result = xB + xA # do something here to get the result return result df['C'] = df.apply(myfunction, axis=1) print (df) ABC 0 1 4 5 1 2 5 7 2 3 6 9 
+9
source

Source: https://habr.com/ru/post/1257606/


All Articles