Reputation: 495
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()
Upvotes: 0
Views: 1547
Reputation: 2881
.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.
Upvotes: 4