我有一个系列,如下所示:
example = pd.Series([[1.0, 1209.75, 1207.25],
[1.0, 1211.0, 1207.5],
[-1.0, 1211.25, 1205.75],
[0, 1207.25, 1206.0],
[1.0, 1206.25, 1201.0],
[-1.0, 1205.75, 1202.75],
[0, 1205.5, 1203.75]])
这个系列基本上在每个单元格中有一个包含 3 个数字的列表。
我把它变成一个 DataFrame 并添加一个新列:
example = example.to_frame(name="input")
example["result"]=np.NaN
现在我想对其执行以下操作:
example["result"] = example["input"].apply(lambda x,y,z: y if x==1 else z if x==-1 else NaN)
尝试执行此操作时收到以下错误消息:
missing 2 required positional arguments: 'y' and 'z'
最佳答案
lambda 只接受一个参数,在这种情况下是一个列表。简单地索引列表:
>>> example["result"] = example["input"].apply(lambda lst: lst[1] if lst[0]==1 else lst[2] if lst[0]==-1 else np.NaN)
>>> example
input result
0 [1.0, 1209.75, 1207.25] 1209.75
1 [1.0, 1211.0, 1207.5] 1211.00
2 [-1.0, 1211.25, 1205.75] 1205.75
3 [0, 1207.25, 1206.0] NaN
4 [1.0, 1206.25, 1201.0] 1206.25
5 [-1.0, 1205.75, 1202.75] 1202.75
6 [0, 1205.5, 1203.75] NaN
简单地说,您可以将嵌套的三元运算符重构为带有嵌套 ifs 的函数,因此您的代码更具可读性:
def func(lst):
x, y, z = lst
if x == 1:
return y
elif x == -1:
return z
else:
return np.NaN
example["result"] = example["input"].apply(func)
关于Python Pandas Lambda : Using multiple variables Lambda within DataFrame,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41433983/