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

如何在numpy.select条件列表中添加ELSE分支覆盖所有剩余场景

实现方法

有两种方式可以完成你要的else逻辑覆盖,效果和你给出的lambda完全一致:

方法1:用np.select原生default参数(最推荐)

np.select自带的default参数本身就是为了处理未匹配所有条件的剩余场景,直接修改原有代码的default值即可:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': [1,2,3,4,5,6,7,8,9],
                   'In': [111, 100, 31, 1100, 12, 33, 21, 32, 33],
                   'Out': [24, 52, 34, 95, 98, 54, 32, 20, 16]})

conditions = [
    df['In'] > 100,
    df['Out'] > 50,
    (df['In'] < df['Out']) & (df['Out'] > 20)
]

choices = [1, 2, 3]

# 把默认值从nan改成你要的else返回值999即可
df['check'] = np.select(conditions, choices, default=999)

方法2:显式把ELSE逻辑加入条件段

如果你要求必须把else逻辑写到conditions列表里,可以在列表最后加一个全匹配的True条件,对应返回值放999即可:

conditions = [
    df['In'] > 100,
    df['Out'] > 50,
    (df['In'] < df['Out']) & (df['Out'] > 20),
    # 全匹配条件必须放在最后,否则会覆盖前面的所有判断逻辑
    pd.Series([True]*len(df), index=df.index)
]

choices = [1, 2, 3, 999]

# 此时default参数可以省略,最后一个条件已经覆盖所有剩余场景
df['check'] = np.select(conditions, choices)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:57:03