python - 对函数中的 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()
如何解决这个问题?
解决方案
使用np.where
:
def test(x, a, b):
return np.where(x>10, a*x+b, 0)
推荐阅读
- python - 我可以在 np.mean() 中使用 str 吗?
- c# - 罗技 G-KEY MACRO SDK(C#):按下鼠标按钮时无法进入配置文件
- linux - Linux:动态加载器选择了错误的库?
- html - 我的类 flex wrap 不适用于 div 项
- javascript - 在 ejs 文件中调用用户定义的 JavaScript 函数
- ruby - 如何使用 Axlsx gem 自动使作为链接的文本成为超链接?
- c# - API:调用 HttpGet 后解析期间 Http 失败
- python - 将 LP 从 Excel 转换为 Python Pulp
- sql - 如何使用 SQL Server Reporting Services URL 访问将呈现的 PDF 报告作为 varbinary 保存到表中
- python - 在 matplotlib 中设置网格线上点之间的距离