I have an array out
. I want to print row numbers which have at least one non-zero element. However, I am getting an error. I present the expected output.
import numpy as np
out = np.array([[ 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. ],
[ 0. , 423.81345923, 0. , 407.01354328,
419.14952534, 0. , 212.13245959, 0. ,
0. , 0. , 0. , 0. ],
[402.93473651, 0. , 216.08166277, 407.01354328,
0. , 414.17017965, 0. , 0. ,
0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. ,
0. , 0. , 0. , 0. ]])
for i in range(0,len(out)):
if (out[i]==0):
print(i)
else:
print("None")
The error is
in <module>
if (out[i]==0):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The expected output is
[1,2]
>Solution :
The issue with your code is that out[i]
is an array. When you check if this array is equal to zero, it returns an array of booleans. The if
statement then returns an error. The following code should work:
solution = []
for idx, e in enumerate(out):
if any(e): # if any element of the array is nonzero
solution.append(idx)
print(solution)
The output is :
[1, 2]
I hope this helps!