You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中DataFrame多条件np.where语句报错的解决方法

解决Pandas中np.where多条件的ValueError问题

错误原因

你遇到的ValueError是因为对Pandas Series使用Python原生or运算符时,Python无法判断整个布尔Series的真假(Series包含多个布尔值),导致歧义性报错。

修正方案

将代码中的or替换为矢量化逻辑或运算符|,同时给每个条件单独加括号(避免运算符优先级导致的逻辑错误),修正后的最后一行代码如下:

df1[col+'_outlier'] = np.where((df1[col]>df1[col+'_upper']) | (df1[col]<df1[col+'_lower']), 1, 0)

完整可运行代码

import pandas as pd
import numpy as np

data = [[99330,12,122],
        [1123,1230,1287],
        [123,101,812739],
        [1143,12301230,252]]
df1 = pd.DataFrame(data, index=['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04'], 
                   columns=['col_A', 'col_B', 'col_C'])
df1.index = pd.to_datetime(df1.index)

for col in df1.columns:
    df1[col+'_mean'] = df1[col].rolling(1).mean().shift()
    df1[col+'_std'] = df1[col].rolling(1).std().shift()
    df1[col+'_upper'] = df1[col+'_mean'] + df1[col+'_std']
    df1[col+'_lower'] = df1[col+'_mean'] - df1[col+'_std']
    # 修正后的异常值判断逻辑
    df1[col+'_outlier'] = np.where((df1[col]>df1[col+'_upper']) | (df1[col]<df1[col+'_lower']), 1, 0)

补充说明

  • 矢量化运算符|会对Series的每个元素逐一进行逻辑判断,返回同长度的布尔Series,符合Pandas的批量处理逻辑;
  • 如果需要逻辑与的条件,对应使用&替代Python原生的and,同样要给每个条件加括号。

内容的提问来源于stack exchange,提问作者MathMan 99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:15:35