首页 > 解决方案 > Series 的真值是模棱两可的

问题描述

当我运行以下函数时,我得到一个系列的真值是模棱两可的错误。环顾网络,它看起来应该可以工作。有什么我想念的吗?我也对如何使用循环中的两列使用列表理解来做到这一点很感兴趣。

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

我看到其他人问过这个问题,我再次问的原因是我的代码与pandas 数据框中的多个 if else 条件的答案相同,并派生多个列

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:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

标签: pythonpandas

解决方案


您可以使用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)    

推荐阅读