问题描述
我正在尝试使用 pyplot 在 Python 中绘制一个函数,问题可以归结为:
I am trying to plot a function in Python with pyplot, where the problem could be boiled down to this:
import numpy as np
import matplotlib.pyplot as plt
def func(x):
if x<0:
return x*x
interval = np.arange(-4.0,4.0,0.1)
plt.plot(interval, func(interval))
plt.show()
抛出以下错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我怎样才能避免这种情况?
How can I avoid this?
推荐答案
如果要更改零以下的值,可以使用 np.where
:
If you wanted to change the values that are below zero you could use np.where
:
import numpy as np
def func(x):
return np.where(x < 0, x*x, x)
print(func(np.arange(-4, 5))) # array([16, 9, 4, 1, 0, 1, 2, 3, 4])
如果您只希望值小于零,则可以使用使用布尔数组建立索引:
If you just wanted the values below zero you could use indexing with a boolean array:
def func(x):
return x[x<0] ** 2
print(func(np.arange(-4, 5))) # array([16, 9, 4, 1])
更笼统: numpy.array
上的比较运算符只返回一个布尔数组:
More general: comparison operators on numpy.array
s just return a boolean array:
>>> arr > 2
array([False, False, True], dtype=bool)
>>> arr == 2
array([False, True, False], dtype=bool)
还有例外
ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all()
在你执行 bool(somearray)
时发生.在很多情况下, bool()
调用是隐式的(因此发现它可能不是立即明显的).这种隐式 bool()
调用的例子是 if
、while
、and
和 or
>:
happens when you do bool(somearray)
. In a lot of cases the bool()
call is implicit (so it may not be immediatly obvious to spot it). Examples of this implicit bool()
call are if
, while
, and
and or
:
>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
在您的情况下,如果x<0 是发生异常的原因,因为 x<0
返回一个布尔数组,然后 if
尝试获取该数组的 bool()
.如上例所示,该异常将引发您的异常.
In your case the if x < 0
was the reason for the exception because x < 0
returns a boolean array and then if
tried to get the bool()
of that array. Which as shown in the example above throws the exception you got.
这篇关于带有运算符 < 的数组的 Pyplot或 >的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!