I’m trying to do an array operation with numpy.nditer, but don’t get the expected result.
My code is
import numpy as np
arr1 = - np.random.random((2,2))
arr2 = np.random.random((2,2))
arr = np.zeros((2,2))
it = np.nditer([arr1, arr2, arr], [], [['readonly'], ['readonly'], ['writeonly']])
for a1, a2, a in it:
a = a1 if -a1 < a2 else a2
print arr
print it.operands[2]
I’m getting all zero results in both arr and it.operands[2], but I expected values from either arr1 or arr2. What would be the correct way to assign values to arr in the iteration?
Doing
a =in Python will simply rebind the local variablea; it won’t affect whatacontains.With
nditer, the iteration variablesa1,a2andaare actually 0-d arrays. Thus, to changea, use the (slightly odd)a[()] =syntax:Note, though, that your whole code can be simplified greatly by using
np.where: