Multi-input Pandas fucntion

Question:

I have a simple dataframe in pandas

     A     B
0    34    23
1    55    65

I know how to write a simple fuction, for example

def mult_function(x):
    return 2*x

df['C']=df['A'].apply(mult_function) 

Giving

     A     B    C
0    34    23   46
1    55    65   130

Is there a way I can make this more complex with multiple input columns

so

def mult_function(....):
output=(2*A) + (3*B)
return output

df['C']=df[....].apply(mult_function) 
Asked By: fred.schwartz

||

Answers:

def mult_function(A, B):
    return 2 * A + 3 * B

df = pd.DataFrame({'A': [34, 55], 'B': [23, 65]})

df['C'] = df.apply(lambda x: mult_function(x.A, x.B), axis=1)
print(df)

or

def mult_function(x):
    return 2 * x.A + 3 * x.B

df = pd.DataFrame({'A': [34, 55], 'B': [23, 65]})

df['C'] = df.apply(mult_function, axis=1)
print(df)

Output:

    A   B    C
0  34  23  137
1  55  65  305
Answered By: Алексей Р

I think apply is redundant here. You can do:

df['C'] = 2*df['A'] + 3*df['B']

Output

    A   B    C
0  34  23  137
1  55  65  305
Answered By: inquirer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.