gpt4 book ai didi

python - 系列的真值不明确

转载 作者:行者123 更新时间:2023-12-01 07:15:10 26 4
gpt4 key购买 nike

当我运行以下函数时,出现“系列的真值不明确”错误。环顾网络,看起来应该可行。我有什么遗漏的吗?我也对如何使用列表理解和循环中的两列来做到这一点感兴趣。

我尝试过使用 and 和 & 得到一些东西。我尝试放置 .any() 但它只使用第一个语句。我查看了 np.where 但我需要它与 3 个 if 语句一起使用,但我对此没有运气。

我看到其他人问过这个问题,我再次问的原因是我的代码与 multiple if else conditions in pandas dataframe and derive multiple columns 的答案相同。

def before_after(df,col1, col2):
if ((df[col1] >= 0) and (df[col2] >= 0)):
return (((df[col2]-df[col1])/df[col1])*100)
elif ((df[col1] < 0) and (df[col2] > 0)):
return (((df[col2]-df[col1])/(df[col1].abs()))*100)
elif ((df[col1] < 0) and (df[col2] < 0)):
return (((df[col2]-df[col1])/df[col1])*100)

错误是:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

最佳答案

您可以使用numpy.select链接的第一个和第三个条件由 | 进行按位 OR,因为相同的返回,即使没有条件匹配,也会返回一些默认值,例如NaN:

def before_after(df,col1, col2):
m1 = (df[col1] >= 0) & (df[col2] >= 0)
m2 = (df[col1] < 0) & (df[col2] > 0)
m3 = (df[col1] < 0) & (df[col2] < 0)

s1 = ((df[col2]-df[col1])/df[col1])*100
s2 = ((df[col2]-df[col1])/(df[col1].abs()))*100

return np.select([m1 | m3, m2], [s1, s2], default=np.nan)

关于python - 系列的真值不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58012666/

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