0

For example lets say I have a df

a    b     c       

1    3     5       
5    9     4      

and I have ifconditions:

if a < 2:
   3
elif  a < 3:
   4
else: b + c

How do I test the conditions and returns a result for each row of my df like below?

a    b     c    d

1    3     5    3 
5    9     4    13

edit: Ideally I want to create a function that allows me to

def function(a, b, c) df['d'] = function(a, b, c)

and calculate for all rows of data. Because in the actual data, there is 100+ condition statements and 10s of columns.

IDontKnowAnything
  • 195
  • 2
  • 3
  • 10
  • 1
    check with np.select – BENY Jan 14 '19 at 16:53
  • Look at [this answer](https://stackoverflow.com/a/53505512/9209546) from possible duplicate [pandas create new column based on values from other columns](https://stackoverflow.com/questions/26886653/pandas-create-new-column-based-on-values-from-other-columns). – jpp Jan 14 '19 at 16:56

2 Answers2

1

you can use apply method:

def custom_calc(x, a , b):
    if x[0] < 2:
        return 3

    if x[0] > 3:
        return x + a + b

df.a = df[['a', 'b', 'c']].apply(func=check, args=(df.b,df.c))

edit the custom function as you wish

masasa
  • 260
  • 1
  • 9
1

You could use apply function along axis 1.

def f(row):
    if row['a'] > 2:
        return 3
    elif row['a'] > 3:
        return 4
    else:
        return  row['b']+row['c']


df.apply(f,axis=1)

#output
0    8
1    3
dtype: int64
Venkatachalam
  • 16,288
  • 9
  • 49
  • 77