Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print all rows of an array not equal to zero in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading