zl程序教程

您现在的位置是:首页 >  其他

当前栏目

pandas进行多条件过滤时可能出现的优先级bug,导致程序无法运行

BUGpandas程序 进行 运行 无法 出现 可能
2023-09-11 14:20:29 时间

pandas进行多条件过滤时可能出现的优先级bug,导致程序无法运行

当我们进行pandas 多条件过滤时,可能会出像这样的报错

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() 和 cannot compare a dtyped [float64] array with a scalar of type [bool]

诸如下面的代码会出错

实例代码

print(df[df['Survived']==1 & df['Age']>30])

写法不一样会报不同的错误

print(df[ df['Age']>30 & df['Survived']==1])

这两种写法分别对应上面两个报错
cannot compare a dtyped [float64] array with a scalar of type [bool] 和 ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any()
原因就在于运算符 == 和 < 优先级 顺序小于 & 所以犯了很严重的错误

那么如何解决呢
改成如下代码,通过()更改优先级顺序就可以达到多条件过滤的目的

print(df[(df['Age']>30) & (df['Survived']==1)])