I am learning python and numpy. While trying to predict a result to check my understanding, I come across this :
import numpy as np
x = np.arange(1,10).reshape(3,3)
np.where(x>5) == (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2]))
And the correlated error I now understand why.
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
And I came up with this:
all(map(np.array_equal,
np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2])) ))
all([np.array_equal(v,t) for (v,t) in zip(
np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2]))) ])
all([(v==t).all() for (v,t) in zip(
np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2]))) ])
Which work, but seems to me a bit tedious and hard to read. Is there a more pythonic or numpy way to test arrays within a tuple ?
CodePudding user response:
You were pretty close. The following works:
np.array_equal(np.where(x>5), (np.array([1, 2, 2, 2]), np.array([2, 0, 1, 2])))
np.array_equal
has the ability to broadcast over tuples. It also treats arrays and sequences as equivalent, so you could just use if you'd prefer:
np.array_equal(np.where(x>5), ([1, 2, 2, 2], [2, 0, 1, 2]))