3

I want to learn how to use lambdas with this type of setting without using a for loop which a function takes arguments from rows of two columns of the dataframe and write the result to another column.

import pandas as pd

df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})

print(df)

df["C"] = ""

print(df)

def add_num(num1 ,num2):
    return num1 + num2

for i in range(len(df)):
   df["C"][i] = add_num(df["A"][i], df["B"][i])
print(df)
0

3 Answers 3

2

You can call apply on the df passing arg axis=1 this will iterate row wise, you can then sub-select the columns of interest in the lambda to pass to your func:

In [49]:    
df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
df["C"] = ""
​
def add_num(num1 ,num2):
    return num1 + num2
​
df["C"] = df.apply(lambda x: add_num(x["A"],  x["B"]), axis=1)
print(df)

   A  B  C
0  1  2  3
1  2  3  5
2  3  4  7

Note that one should avoid using apply, most operations can be performed using vectorised methods, I know this is just for learning but you should look for a numpy or other ufunc that is vectorised

Sign up to request clarification or add additional context in comments.

3 Comments

One more question=) Does this version have a performance difference than the for loop version?
No, that's not true. Calling lambda that forwards to add_num function when called will be slower than directly calling add_num in the loop. However it may be that the loop is a bit more efficient with apply. But my guess is that the abstraction with lambda will be slower.
@MSeifert I was referring to the apply not the lambda portion
0

This should do it:

import pandas as pd

df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})

def add_num(num1 ,num2):
    return num1 + num2

df['C'] = df.T.apply(lambda x: add_num(x['A'], x['B']))

Comments

0

The obvious answer would be: don't use lambda when more simple expressions work:

df['C'] = df['A'] + df['B']

Because that will use vectorized operations.

The approach with lambda and apply is already covered by @EdChum's answer so I won't show it again.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.