使用if语句优化作用于numpy数组的函数

编程入门 行业动态 更新时间:2024-10-22 23:00:29
本文介绍了使用if语句优化作用于numpy数组的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个类似的代码:

Suppose I have a code like:

import numpy as np def value_error(x): if x > 10: return 0. else: return np.sin(x)

如果调用numpy数组,这可能会给我一个ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

This could give me a ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() if called upon an numpy array.

现在我可以改为:

def alright(x): return np.sin(x) * (x <= 10.) print alright(np.ones(100) * 100) print value_error(np.ones(100) * 10)

我的功能(在本例中为np.sin)可能是一个昂贵的功能.但是,它会调用x的每个元素,即使我知道答案的因为x > 10的元素也是如此,而无需进行昂贵的调用.我如何才能两全其美?

My function (in this case np.sin) could be an expensive one. It is, however, called for every element of x, even ones where I know the answer because x > 10, without an expensive call. How can I get the best of both worlds?

推荐答案

这是一个基于掩码的掩码,只能在有效掩码上与np.sin一起使用-

Here's a mask based one that operates with np.sin only on the valid ones -

out = np.zeros(x.shape) mask = x <= 10 out[mask] = np.sin(x[mask])

利用 numexpr模块更快transcendental操作-

import numexpr as ne out = np.zeros(x.shape) mask = x <= 10 x_masked = x[mask] out[mask] = ne.evaluate('sin(x_masked)')

更多推荐

使用if语句优化作用于numpy数组的函数

本文发布于:2023-10-25 13:45:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527124.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   语句   函数   作用于   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!