Crib Notes: How to Apply a User Defined Function to Multiple Columns in a Pandas Data Frame
Published in
1 min readNov 18, 2019
Let’s start with a data frame that has two columns:
import pandas as pddf = pd.DataFrame({'A' : [1,2,4], 'B' : [2,2,2]})
Then:
1. We define a function, doSomething, that has two inputs, x and y.
def doSomething(x, y):
returnValue = float(x*y) + 13
return returnValue
2. Apply the function to the two columns , A and B, of the data frame df .
df[['A', 'B]].apply(lambda x: doSomething(*x), axis = 1)
3. Save the function output into a new column, column C.
df['C'] = df[['A', 'B]].apply(lambda x: doSomething(*x), axis = 1)
And we end up with the data frame df: