将具有常数参数的函数应用于pandas数据框 [英] apply function with constant parameter to pandas dataframe
本文介绍了将具有常数参数的函数应用于pandas数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个pandas数据框,并且创建了一个函数.我想将此功能应用于数据框的每一行.但是,该函数具有第三个参数,该参数不是来自数据帧,而且可以说是恒定的.
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)
我认为我必须使用apply函数,但是我看不到如何传递此常量参数.
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
推荐答案
在 c
列中我得到了一些不同的输出.如果需要按行处理,请将 axis = 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
这篇关于将具有常数参数的函数应用于pandas数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文