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

1

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.