首页 > 解决方案 > 为什么我会收到 ValueError:Series 的真值不明确?

问题描述

我知道之前有人问过类似的问题,但我很难理解为什么会出现这个错误。

我正在使用下面的代码创建一个新列,如果“价格”在上限“price_h2”和下限“price_h1”之内,则该行被标记为异常值

df_test['price_outlier'] = np.where( df_test['price_h1'] <= df_test['price'] <= df_test['price_h2'],'normal','outlier')

非常感谢帮助!

标签: pythonpandasnumpy

解决方案


因为 numpy 数组不支持语法: a < x < b

您需要使用括号来分隔两个子句(a < x) & (x < b)

df_test['price_outlier'] = np.where((df_test['price_h1'] <= df_test['price']) &\
                                    (df_test['price'] <= df_test['price_h2']), 
                                    'normal', 'outlier')

推荐阅读