I have an array A
with shape (3,3,3)
. I want to print A[0], A[1], A[2]
only when at least one of the elements of A[0], A[1], A[2]
is <=10 or>=30
. But I am getting an error. The expected output is attached.
import numpy as np
A=np.array([[[41,42,43],[44,45,46],[47,48,49]],[[11,12,13],[14,15,16],[17,18,19]],
[[31,32,33],[34,35,36],[37,38,39]]])
for t in range(0,len(A)):
if(A[t]<=10 or A[t]>=30):
print(A[t])
else:
print("STOP")
The error is
in <module>
if(A[t]<=10 or A[t]>=30):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The expected output is
array([[41, 42, 43],
[44, 45, 46],
[47, 48, 49]]) #since no single element of A[0] satisfy <=10 or>=30.
STOP #since A[1] satisfies <=10 or>=30.
CodePudding user response:
Use all()
as you want to satisfy each value with the condition.
import numpy as np
A = np.array([[[41, 42, 43],
[44, 45, 46],
[47, 48, 49]],
[[11, 12, 13],
[14, 15, 16],
[17, 18, 19]],
[[31, 32, 33],
[34, 35, 36],
[37, 38, 39]]])
for i in range(len(A)):
if (A[i] <= 10).all() or (A[i] >= 30).all():
print(A[i])
else:
print("STOP")
Output
[[41 42 43]
[44 45 46]
[47 48 49]]
STOP
[[31 32 33]
[34 35 36]
[37 38 39]]
CodePudding user response:
The iterator will be returning an entire 'row' (or whatever that is in three dimensions), not a single element. If you put:
print(A[t])
in before the test, you'll see what you're checking against:
[[41 42 43]
[44 45 46]
[47 48 49]]
so you'll need to 'dig in' to the array a little more by having nested loops.