Proper use of numpy.nditer?

I am trying to perform an array operation with numpy.nditer , but not getting the expected result.

My code

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 get all null results in both arr and it.operands[2] , but I was expecting values ​​from arr1 or arr2 . What would be the proper way to assign arr values ​​in an iteration?

+4
source share
1 answer

Doing a = in Python will simply restore the local variable a ; it will not affect what a contains.

With nditer , the iteration variables a1 , a2 and a are actually 0-d arrays. Thus, to change a , use the syntax (slightly odd) a[()] = :

 for a1, a2, a in it: a[()] = a1 if -a1 < a2 else a2 

Note, however, that all of your code can be simplified using np.where :

 import numpy as np arr1 = - np.random.random((2,2)) arr2 = np.random.random((2,2)) arr = np.where(-arr1 < arr2, arr1, arr2) 
+5
source

Source: https://habr.com/ru/post/1440615/


All Articles