Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply function with constant parameter to pandas dataframe

I have a pandas dataframe, and I created a function. I would like to apply this function to each row of the dataframe. However the function has a third parameter that does not come from the dataframe and is constant so to say.

import pandas as pd

df = pd.DataFrame(data = {'a':[1, 2, 3], 'b':[4, 5, 6]})

def add(a, b, c):
    return a + b * c

df['c'] = add(df['a'], df['b'], 2)

I think I have to use the apply function but I don't see how I would pass this constant argument.

print df
>>    a  b   c
>> 0  1  4  10
>> 1  2  5  14
>> 2  3  6  18
like image 687
ArnJac Avatar asked Oct 10 '17 12:10

ArnJac


1 Answers

I get a bit different output in c column. If need process by rows add axis=1 to apply:

df['c'] = add(df['a'],df['b'],2)
df['d'] = df.apply(lambda x: add(x['a'], x['b'], 2), axis=1)
print (df)
   a  b   c   d
0  1  4   9   9
1  2  5  12  12
2  3  6  15  15

def add(a,b,c):
    #operator precedence, need ()
    return (a + b) * c

df['c'] = add(df['a'],df['b'],2)
df['d'] = df.apply(lambda x: add(x['a'], x['b'], 2), axis=1)
print (df)
   a  b   c   d
0  1  4  10  10
1  2  5  14  14
2  3  6  18  18
like image 54
jezrael Avatar answered Nov 14 '22 23:11

jezrael