A. wadhawan A. wadhawan - 1 year ago 73
Python Question

How to loop inside a nd.array in Python

I have a N Dimensional array = X, I want to check each value in X if it is greater than 0.35 . I write as :-

for number in X:
if (.35> number): # Here error occurs
print (enumerate(number))

But I get this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I want to save the index of each value in X that is less than 0.35 in a list

Answer Source

When working with NumPy you must always strive to operate in vector space. That means not writing for loops, nor in, etc.

For your present case, you can do this:

print(X[X < 0.35])

This will be massively faster than writing a loop. If you have to have them print on separate lines, you can:

values = X[X < 0.35]
np.savetxt(sys.stdout, values)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download