Efficient multidimensional iterator object to iterate over arrays.
Parameters :  op : ndarray or sequence of array_like
flags : sequence of str, optional
op_flags : list of list of str, optional
op_dtypes : dtype or tuple of dtype(s), optional
order : {‘C’, ‘F’, ‘A’, or ‘K’}, optional
casting : {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional
op_axes : list of list of ints, optional
itershape : tuple of ints, optional
buffersize : int, optional


Notes
nditer supersedes flatiter. The iterator implementation behind nditer is also exposed by the Numpy C API.
The Python exposure supplies two iteration interfaces, one which follows the Python iterator protocol, and another which mirrors the Cstyle dowhile pattern. The native Python approach is better in most cases, but if you need the iterator’s coordinates or index, use the Cstyle pattern.
Examples
Here is how we might write an iter_add function, using the Python iterator protocol:
def iter_add_py(x, y, out=None):
addop = np.add
it = np.nditer([x, y, out], [],
[['readonly'], ['readonly'], ['writeonly','allocate']])
for (a, b, c) in it:
addop(a, b, out=c)
return it.operands[2]
Here is the same function, but following the Cstyle pattern:
def iter_add(x, y, out=None):
addop = np.add
it = np.nditer([x, y, out], [],
[['readonly'], ['readonly'], ['writeonly','allocate']])
while not it.finished:
addop(it[0], it[1], out=it[2])
it.iternext()
return it.operands[2]
Here is an example outer product function:
def outer_it(x, y, out=None):
mulop = np.multiply
it = np.nditer([x, y, out], ['external_loop'],
[['readonly'], ['readonly'], ['writeonly', 'allocate']],
op_axes=[range(x.ndim)+[1]*y.ndim,
[1]*x.ndim+range(y.ndim),
None])
for (a, b, c) in it:
mulop(a, b, out=c)
return it.operands[2]
>>> a = np.arange(2)+1
>>> b = np.arange(3)+1
>>> outer_it(a,b)
array([[1, 2, 3],
[2, 4, 6]])
Here is an example function which operates like a “lambda” ufunc:
def luf(lamdaexpr, *args, **kwargs):
"luf(lambdaexpr, op1, ..., opn, out=None, order='K', casting='safe', buffersize=0)"
nargs = len(args)
op = (kwargs.get('out',None),) + args
it = np.nditer(op, ['buffered','external_loop'],
[['writeonly','allocate','no_broadcast']] +
[['readonly','nbo','aligned']]*nargs,
order=kwargs.get('order','K'),
casting=kwargs.get('casting','safe'),
buffersize=kwargs.get('buffersize',0))
while not it.finished:
it[0] = lamdaexpr(*it[1:])
it.iternext()
return it.operands[0]
>>> a = np.arange(5)
>>> b = np.ones(5)
>>> luf(lambda i,j:i*i + j/2, a, b)
array([ 0.5, 1.5, 4.5, 9.5, 16.5])
Attributes
dtypes  
finished  
has_delayed_bufalloc  
has_index  
has_multi_index  
iterationneedsapi  
iterindex  
itersize  
ndim(a)  Return the number of dimensions of an array. 
nop  
operands  
shape(a)  Return the shape of an array. 
Methods
copy(a)  Return an array copy of the given object. 
debug_print  
enable_external_loop  
iternext  
next  
remove_axis  
remove_multi_index  
reset 