0

I am writing a simple loop to get the max value inside an array.

I know there is the function arr.max() but I'm just curious why the following code does not work.

import numpy as np
arr1 = np.arange(0,9).reshape(3,3)

max_value = arr1[0]
for i in arr1:
    if max_value > i:
        max_value = i
print(max_value)

which gives me:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last) <ipython-input-80-9fb1fcfa0948> in <module>
       1 max_value = arr1[0]
       2 for i in arr1:
 ----> 3     if i > max_value:
       4         max_value = i

 ValueError: The truth value of an array with more than one element is
 ambiguous. Use a.any() or a.all()
1
  • 2
    I think you also have a typo in your question. "max_value > i" should be "i > max_value" on line 6. Commented Mar 5, 2020 at 10:44

1 Answer 1

4

.reshape(3,3) reshapes your array, so it ends up being a two-dimensional 3×3 array:

>>> print(arr1)
[[0 1 2]
 [3 4 5]
 [6 7 8]]

As a result, arr1[0] isn’t a scalar, it’s itself a three-element array. You’d have to iterate over that again to find the maximum value.

Sign up to request clarification or add additional context in comments.

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.