gpt4 book ai didi

Python Pandas Lambda : Using multiple variables Lambda within DataFrame

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:38 27 4
gpt4 key购买 nike

我有一个系列如下:

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)

我在尝试执行此操作时收到以下错误消息:缺少 2 个必需的位置参数:“y”和“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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com