3

I have a dataframe df

import pandas
df = pandas.DataFrame(data=[[1,True],[2,False]],columns=['A','decide'])

to which rows I want to apply a function fun depending on the value of the decide column

def fun(case,var):
   case = case + var
   return case


df=df.apply(lambda x: fun(x,1) if x['decide'] else fun(x,2))

of course doesn't work :) any idea why and how to make it working?

1
  • 1
    please share expected output Commented Feb 21, 2019 at 16:22

2 Answers 2

4

Try to fix your code , PS : You forget to add axis=1

df.apply(lambda x: fun(x['A'],1) if x['decide'] else fun(x['A'],2),axis=1)
Out[560]: 
0    2
1    4
dtype: int64

Also When you using np.where you still can pass your own defined functions

np.where(df.decide,fun(df.A,1),fun(df.A,2))

If you logic is as simple as you show to us in your sample function

df.A+2-df.decide
Out[563]: 
0    2
1    4
dtype: int64
Sign up to request clarification or add additional context in comments.

Comments

4

IIUC you can use np.where:

df['A'] = np.where(df.decide, df.A+1, df.A+2)

   A  decide
0  2    True
1  4   False

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.