首页 > 解决方案 > 对函数中的 if 检查进行矢量化

问题描述

我在 Python 中有一个函数,其中包含一个if检查

def test(x, a, b):
   if(x>10):
      y = a*x+b
   else:
      y = 0
   return y

问题是我必须x作为向量传递并获得向量化y输出。我收到以下混合x值错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如何解决这个问题?

标签: pythonnumpy

解决方案


使用np.where

def test(x, a, b):
    return np.where(x>10, a*x+b, 0)

推荐阅读