具有if语句的Numpy数组的功能 [英] Function of Numpy Array with if-statement

查看:87
本文介绍了具有if语句的Numpy数组的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Matplotlib Numpy 产生一些情节.我希望定义一个函数,给定一个数组,该函数将返回另一个使用 elementwise 计算得出的值的数组,例如:

I am using Matplotlib and Numpy to produce some plots. I wish to define a function which given an array returns another array with values calculated elementwise, for example:

def func(x):
     return x*10

x = numpy.arrange(-1,1,0.01)
y = func(x)

这很好.但是现在我希望在func中包含一个if语句,例如:

This is fine. Now however I wish to have an if-statement inside func, for example:

def func(x):
     if x<0:
          return 0
     else:
          return x*10

x = numpy.arrange(-1,1,0.01)
y = func(x)

不幸的是,这引发了以下错误

This unfortunately throws the following error

Traceback (most recent call last):
  File "D:\Scripts\test.py", line 17, in <module>
    y = func(x)
  File "D:\Scripts\test.py", line 11, in func
    if x<0:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我查看了 all()

I looked at the documentation for all() and any() and they do not fit the bill for what I need. So is there a nice way to make the function handle arrays element wise as in the first example?

推荐答案

使用 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆