np.where多条件筛选_np.where性能优化

�� 刚学Python的�白是�是总被一堆if-else�晕?尤其�对数组数�时,写循�慢到怀疑人生…别慌�​​NumPy的np.where​​ 就是专治这�痛点的�器�今天手把手教你用它的多�件技巧,​​�速50�​​还能少写80%代��


� 什么是np.where?简�到哭的比喻�

想象你有一�苹��和一�橘��,��说:“��丢�,好�按�类分开放�� —— ​​np.where就是自动化分拣机​​�

  • ​​å�•æ�¡ä»¶æ¨¡å¼�​​:np.where(æ°´æ�œ==好æ�œ, ä¿�å­˜, 丢æ�‰)
  • ​​多æ�¡ä»¶æ¨¡å¼�​​:np.where((æ°´æ�œ==苹æ�œ)&(好æ�œ), 放红ç­�, np.where(...))
    看,​​�件组�直�用&(�)�|(或)​​,�用写循�就能批��作�

💡 ​​个人踩�心得​​:别�用and/or�必须用​​&�|​​,�则报错到你哭�括�也得包严�,比如(�件A) & (�件B)


🚀 多�件筛选�战:3�高频场景

场景1:学生�绩分级(90分以上A,80-89分B...)

python�行�制
import numpy as np  
scores = np.array([88, 92, 75, 60, 45, 70])  
# 嵌套np.where��多级分类  
grade = np.where(scores >= 90, "A",  
              np.where(scores >= 80, "B",  
                   np.where(scores >= 70, "C", "D")))  
print(grade)  # 输出: ['B' 'A' 'C' 'D' 'D' 'C']  

​​关键点​​:​​�严格�件开始嵌套​​(比如先判≥90,�判≥80)


场景2:电商库存过滤(价格>100且库存<10的商�打标)

python�行�制
prices = np.array([150, 80, 200, 99])  
stocks = np.array([5, 20, 8, 15])  
# &组���件,一次性输出标签  
tag = np.where((prices > 100) & (stocks < 10), "紧急补货", "正常")  
print(tag)  # 输出: ['紧急补货' '正常' '紧急补货' '正常']  

​​��​​:​​�件数组形状必须一致​​��则广播机制失效


场景3:图�阈值分割(红色通�>200且�色<50的�素�白)

python�行�制
# 模拟RGB图� (3x3�素)  
image = np.array([[[255, 30, 40], [200, 100, 50]],  
                  [[30, 220, 10], [10, 50, 250]]])  
# 拆解RGB通�  
red = image[:, :, 0]  
blue = image[:, :, 2]  
# 多�件定��素  
white_mask = np.where((red > 200) & (blue < 50), 255, image)  

👉 ​​输出效�​​:仅满足�件的�素��纯白,其余�留�图


⚡ 性能优化秘�:�速50��是梦�

对比�验:10万数��处�

python�行�制
import time  
data = np.random.rand(100000)  # 10万个�机数  

# Python循�版  
start = time.time()  
result_loop = [x*2 if x>0.5 else x/2 for x in data]  
print(f"循�耗时: {time.time()-start:.4f}秒")  

# np.where版  
start = time.time()  
result_np = np.where(data > 0.5, data*2, data/2)  
print(f"np.where耗时: {time.time()-start:.4f}秒")  

​​结�惊呆​​:

  • 循ç�¯è€—时:​​0.39秒​​
  • np.where耗时:​​0.008秒​​ 👉 ​​速度æ��å�‡48å€�ï¼�​​

✅ 3个优化�则(附��指�)

  1. ​​����计算�件​​
    � 错误写法:np.where(data>0.5, data*2, data/2) + �续�算data>0.5
    ✅ 正确�法:​​预存�件��​​ → condition = data>0.5,�续�用

  2. ​​高维数�用索引代替嵌套​​

    python�行�制
    # �效嵌套  
    result = np.where(cond1, x, np.where(cond2, y, z))  
    # 高效方案:用索引直�定�  
    result = choices[np.where(conditions)]  # choices=[x,y,z]  
  3. ​​别在np.where里调��函数​​�
    ⚠� 例如:np.where(x>0, heavy_func(x), 0)
    问题:​​heavy_func会全�执行​​,浪费资��
    改用:​​先计算�赋值​​ → y = heavy_func(x); np.where(x>0, y, 0)


� 独家进阶:多�件+广播机制结�

当�件值和输出值形状��时,​​广播机制自动对�​​�

python�行�制
# 二维�件 + 一维值  
cond_2d = np.array([[True, False], [False, True]])  
# 自动广播:True�置�[10,20]中对应索引的值  
result = np.where(cond_2d, [10, 20], 0)  
print(result)  # 输出:[[10, 0], [0, 20]]   

​​应用场景​​:比如对矩阵��列用��阈值处�,​​一行代��定​​�


🌟 ​​终�建议​​:

  • ​​简å�•æ�¡ä»¶â€‹â€‹ → ç›´æ�¥ç”¨&ã€�|组å�ˆ
  • ​​超多分支​​ → 改用np.select([cond1,cond2], [choice1,choice2], default)
  • ​​性能瓶颈​​ → å’Œnumba编译加速æ�­é…�使用,轻æ�¾å¤„ç�†â€‹â€‹å�ƒä¸‡çº§æ•°æ�®â€‹â€‹ï¼�

相关文章

zui-xin