问题
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