Home > Back-end >  Multi-input Pandas fucntion
Multi-input Pandas fucntion

Time:08-27

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) 

CodePudding user response:

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

CodePudding user response:

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
  • Related