Lambda with two values does not work, error: <lambda>() missing 1 required positional argument: 'y)
Lambda with two values does not work, error: <lambda>() missing 1 required positional argument: 'y)
我有一个数据框:
data = {'key': ['one', 'two', 'zero'], 'cost': [300, 20, 500], 'leads': [20, 0, 50]}
data = pd.DataFrame(data=data)
我想通过如下所示的函数计算新值:
def cpl_calc(x, y):
if x == 0:
cpl = y
else:
cpl = y / x
print(cpl)
当我尝试这样数数时:
data['cpl'] = data[['cost', 'leads']].apply(lambda x, y: cpl_calc(x, y))
我看到以下错误 TypeError: () missing 1 required positional argument: 'y'
如何让公式正确计算新值?
对于您的情况,您可以使用矢量化:
data['cost'].where(data['leads'] == 0, other=data['leads'] / data['cost'])
print(data)
# Output
key cost leads cpl
0 one 300 20 0.066667
1 two 20 0 20.000000
2 zero 500 50 0.100000
正如@Corralien 所说,最好将其矢量化。看到那个答案。但是要了解如何通过 apply()
函数执行此操作,您可以:
def cpl_calc(x):
if x['cost'] == 0:
cpl = x['leads']
else:
cpl = x['leads'] / x['cost']
return cpl
data.apply(cpl_calc, axis=1)
0 0.066667
1 0.000000
2 0.100000
我有一个数据框:
data = {'key': ['one', 'two', 'zero'], 'cost': [300, 20, 500], 'leads': [20, 0, 50]}
data = pd.DataFrame(data=data)
我想通过如下所示的函数计算新值:
def cpl_calc(x, y):
if x == 0:
cpl = y
else:
cpl = y / x
print(cpl)
当我尝试这样数数时:
data['cpl'] = data[['cost', 'leads']].apply(lambda x, y: cpl_calc(x, y))
我看到以下错误 TypeError: () missing 1 required positional argument: 'y'
如何让公式正确计算新值?
对于您的情况,您可以使用矢量化:
data['cost'].where(data['leads'] == 0, other=data['leads'] / data['cost'])
print(data)
# Output
key cost leads cpl
0 one 300 20 0.066667
1 two 20 0 20.000000
2 zero 500 50 0.100000
正如@Corralien 所说,最好将其矢量化。看到那个答案。但是要了解如何通过 apply()
函数执行此操作,您可以:
def cpl_calc(x):
if x['cost'] == 0:
cpl = x['leads']
else:
cpl = x['leads'] / x['cost']
return cpl
data.apply(cpl_calc, axis=1)
0 0.066667
1 0.000000
2 0.100000