简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM