在Pandas中使用NumPy where调用max()时触发歧义真值错误
问题解决:Pandas中np.where结合max避免负值报错
错误原因
Python内置的max()函数仅支持标量值之间的比较,而df["col 1"]-df["col 2"]返回的是Pandas Series(一组向量值)。直接将Series与标量0传入max()时,函数无法判断整个Series的布尔值,因此抛出the truth value of a series is ambiguous. Use a.empty(), a.bool(), a.item(), a.any() or a.all().错误。
解决方案
方案1:使用NumPy的np.maximum()(推荐)
np.maximum()支持向量化操作,可直接对Series和标量进行逐元素比较,返回对应位置的较大值:
import numpy as np import pandas as pd def function(df): df["new col"] = np.where(df["col 1"] > 10, np.maximum(df["col 1"] - df["col 2"], 0), 0) return df
方案2:使用Pandas的clip()方法
clip(lower=0)可以将Series中小于0的值替换为0,同样实现避免负值的效果:
import pandas as pd import numpy as np def function(df): diff = df["col 1"] - df["col 2"] df["new col"] = np.where(df["col 1"] > 10, diff.clip(lower=0), 0) return df
方案3:嵌套np.where
通过两层np.where实现与max类似的逻辑,先判断差值是否大于0,再返回对应结果:
import numpy as np import pandas as pd def function(df): diff = df["col 1"] - df["col 2"] df["new col"] = np.where(df["col 1"] > 10, np.where(diff > 0, diff, 0), 0) return df
内容的提问来源于stack exchange,提问作者jess
相关产品推荐
相关产品推荐

