Reputation: 59
I have two numpy arrays and I'm trying to find the greater of them (element wise, i.e. all elements should be greater)
import numpy as np
a = np.array([4,5,6])
b = np.array([7,8,9])
if b > a:
print 'True'
But I'm not getting the desired output and getting an error
Upvotes: 0
Views: 1447
Reputation: 177078
b > a
produces an array containing True
/False
values.
However, Python can't determine whether NumPy arrays with more than one element should be True
or False
. How should an array such as array([True, False, True])
be evaluated? A ValueError
is raised because of the potential ambiguity.
Instead, you need to check whether all of the values in b > a
are True
. Use NumPy's all()
to do this:
if (b > a).all():
print 'True'
Upvotes: 1
Reputation: 12418
if all(b>a):
print 'True'
For multi-dimensional arrays, use:
if np.all(b>a):
print 'True'
However all()
is faster for single dimension arrays and may be useful if your arrays are very large:
>>> timeit('a = np.array([4,5,6]); b = np.array([7,8,9]); all(a>b)',number=100000,setup='import numpy as np')
0.34104180335998535
>>> timeit('a = np.array([4,5,6]); b = np.array([7,8,9]); np.all(a>b)',number=100000,setup='import numpy as np')
0.9201719760894775
Upvotes: 1
Reputation: 86356
Use np.all()
In [1]: import numpy as np
In [2]: a = np.array([4,5,6])
In [3]: b = np.array([7,8,9])
In [4]: np.all(b > a)
Out[4]: True
Upvotes: 2