apply function with constant parameter to pandas dataframe

对着背影说爱祢 提交于 2021-02-07 13:36:44

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/46667402/apply-function-with-constant-parameter-to-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!