试图在熊猫中复制一个简单的Excel函数,但没有成功。还没有尝试过np.where(),因为我想学习lambda函数,并尽可能减少对导入的依赖。
可复制的功能:
=+IF([@[Coupa Type]]="freeform","Freeform","Structured PO")Lambda我测试和工作:
lambdatest = lambda x: f"{x} is even" if x % 2 == 0 else f"{x} is odd"兰博达对于熊猫来说是不起作用的:
test = raw[["Coupa Type", "Structured Pos"]]
test["Structured Pos"] = test.apply(
lambda x: "Freeform" if test["Coupa Type"] == "freeform" else "Structured PO"
)错误:
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().我猜想它是试图计算整个列,而不是逐行计算,我如何解决这个问题?
发布于 2021-12-07 15:32:25
我--您需要将axis=1添加到apply()调用中,以便为每一行执行lambda函数,而不是对每一列执行,这是默认的:
test["Structured Pos"] = test.apply(
lambda x: "Freeform" if x["Coupa Type"] == "freeform" else "Structured PO",
axis=1,
)(您还需要在Lambda函数中使用x["Coupa Type"]而不是test["Coupa Type"],就像我前面所做的那样。)
不过,对于这种情况,一个更有效的解决方案是做一些与此相关的工作:
test["Structured Pos"] = test["Coupa Type"].map({"freeform": "Freeform"}).fillna("Structured PO")...because map用字典的值替换字典中作为键的系列中的所有值,而系列中的值不是字典中的键,而是替换为NaN,因此可以使用fillna来提供默认值。
https://stackoverflow.com/questions/70262762
复制相似问题