首页 > 解决方案 > How to use 2 parameters for apply-method in pandas

问题描述

a b c (2*a) d (a+b)
a1 b1 2*a1 ????
a2 b2 2*a2 ????

I don't know how to calculate the column 'd(a+b)' which is used 2 parameters with apply method.

If I want the value of column 'c'(=2*a) which is only 1 parameter, I will script the following code.

def function(x):
    ret = 2*x
    return ret

df['c'] = df['a'].apply(function)

标签: pandas

解决方案


在 lambda 中调用您的方法。

def function(a, b):
    ret = a + b
    return ret

df['d'] = df.apply(lambda row: function(row['a'], row['b']), axis=1)

或者

df['d'] = df.apply(lambda row: row['a'] + row['b'], axis=1)

简单地添加两列也可以

df['d'] = df['a'] + df['b']

推荐阅读