0

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

smci
  • 32,567
  • 20
  • 113
  • 146
HVN19
  • 49
  • 1
  • 6
  • possible duplicate of [Comparing two numpy arrays for equality, element-wise](http://stackoverflow.com/questions/10580676/comparing-two-numpy-arrays-for-equality-element-wise) – smci Jan 31 '15 at 22:40

3 Answers3

2

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
Akavall
  • 82,592
  • 51
  • 207
  • 251
1
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
Jeff
  • 12,147
  • 10
  • 51
  • 87
1

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'
Alex Riley
  • 169,130
  • 45
  • 262
  • 238