bundles / numpy 2.5.0.dev0+git20251130.2de293a / numpy / nditer
class
numpy:nditer
source: /dev/numpy/build-install/usr/lib/python3.14/site-packages/numpy/__init__.py
Signature
class nditer ( op , flags = None , op_flags = None , op_dtypes = None , order = K , casting = safe , op_axes = None , itershape = None , buffersize = 0 ) Summary
Efficient multi-dimensional iterator object to iterate over arrays. To get started using this object, see the introductory guide to array iteration <arrays.nditer>.
Parameters
op: ndarray or sequence of array_likeThe array(s) to iterate over.
flags: sequence of str, optionalFlags to control the behavior of the iterator.
bufferedenables buffering when required.c_indexcauses a C-order index to be tracked.f_indexcauses a Fortran-order index to be tracked.multi_indexcauses a multi-index, or a tuple of indices with one per iteration dimension, to be tracked.common_dtypecauses all the operands to be converted to a common data type, with copying or buffering as necessary.copy_if_overlapcauses the iterator to determine if read operands have overlap with write operands, and make temporary copies as necessary to avoid overlap. False positives (needless copying) are possible in some cases.delay_bufallocdelays allocation of the buffers until a reset() call is made. Allowsallocateoperands to be initialized before their values are copied into the buffers.external_loopcauses thevaluesgiven to be one-dimensional arrays with multiple values instead of zero-dimensional arrays.grow_innerallows thevaluearray sizes to be made larger than the buffer size when bothbufferedandexternal_loopis used.rangedallows the iterator to be restricted to a sub-range of the iterindex values.refs_okenables iteration of reference types, such as object arrays.reduce_okenables iteration ofreadwriteoperands which are broadcasted, also known as reduction operands.zerosize_okallows itersize to be zero.
op_flags: list of list of str, optionalThis is a list of flags for each operand. At minimum, one of
readonly,readwrite, orwriteonlymust be specified.readonlyindicates the operand will only be read from.readwriteindicates the operand will be read from and written to.writeonlyindicates the operand will only be written to.no_broadcastprevents the operand from being broadcasted.contigforces the operand data to be contiguous.alignedforces the operand data to be aligned.nboforces the operand data to be in native byte order.copyallows a temporary read-only copy if required.updateifcopyallows a temporary read-write copy if required.allocatecauses the array to be allocated if it is None in theopparameter.no_subtypeprevents anallocateoperand from using a subtype.arraymaskindicates that this operand is the mask to use for selecting elements when writing to operands with the 'writemasked' flag set. The iterator does not enforce this, but when writing from a buffer back to the array, it only copies those elements indicated by this mask.writemaskedindicates that only elements where the chosenarraymaskoperand is True will be written to.overlap_assume_elementwisecan be used to mark operands that are accessed only in the iterator order, to allow less conservative copying whencopy_if_overlapis present.
op_dtypes: dtype or tuple of dtype(s), optionalThe required data type(s) of the operands. If copying or buffering is enabled, the data will be converted to/from their original types.
order: {'C', 'F', 'A', 'K'}, optionalControls the iteration order. 'C' means C order, 'F' means Fortran order, 'A' means 'F' order if all the arrays are Fortran contiguous, 'C' order otherwise, and 'K' means as close to the order the array elements appear in memory as possible. This also affects the element memory order of
allocateoperands, as they are allocated to be compatible with iteration order. Default is 'K'.casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optionalControls what kind of data casting may occur when making a copy or buffering. Setting this to 'unsafe' is not recommended, as it can adversely affect accumulations.
'no' means the data types should not be cast at all.
'equiv' means only byte-order changes are allowed.
'safe' means only casts which can preserve values are allowed.
'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed.
'unsafe' means any data conversions may be done.
op_axes: list of list of ints, optionalIf provided, is a list of ints or None for each operands. The list of axes for an operand is a mapping from the dimensions of the iterator to the dimensions of the operand. A value of -1 can be placed for entries, causing that dimension to be treated as
newaxis.itershape: tuple of ints, optionalThe desired shape of the iterator. This allows
allocateoperands with a dimension mapped by op_axes not corresponding to a dimension of a different operand to get a value not equal to 1 for that dimension.buffersize: int, optionalWhen buffering is enabled, controls the size of the temporary buffers. Set to 0 for the default value.
Attributes
dtypes: tuple of dtype(s)The data types of the values provided in value. This may be different from the operand data types if buffering is enabled. Valid only before the iterator is closed.
finished: boolWhether the iteration over the operands is finished or not.
has_delayed_bufalloc: boolIf True, the iterator was created with the
delay_bufallocflag, and no reset() function was called on it yet.has_index: boolIf True, the iterator was created with either the
c_indexor thef_indexflag, and the property index can be used to retrieve it.has_multi_index: boolIf True, the iterator was created with the
multi_indexflag, and the property multi_index can be used to retrieve it.indexWhen the
c_indexorf_indexflag was used, this property provides access to the index. Raises a ValueError if accessed andhas_indexis False.iterationneedsapi: boolWhether iteration requires access to the Python API, for example if one of the operands is an object array.
iterindex: intAn index which matches the order of iteration.
itersize: intSize of the iterator.
itviewsStructured view(s) of operands in memory, matching the reordered and optimized iterator access pattern. Valid only before the iterator is closed.
multi_indexWhen the
multi_indexflag was used, this property provides access to the index. Raises a ValueError if accessed accessed andhas_multi_indexis False.ndim: intThe dimensions of the iterator.
nop: intThe number of iterator operands.
operands: tuple of operand(s)The array(s) to be iterated over. Valid only before the iterator is closed.
shape: tuple of intsShape tuple, the shape of the iterator.
valueValue of
operandsat current iteration. Normally, this is a tuple of array scalars, but if the flagexternal_loopis used, it is a tuple of one dimensional arrays.
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 C-style do-while pattern. The native Python approach is better in most cases, but if you need the coordinates or index of an iterator, use the C-style pattern.
Examples
Here is how we might write an ``iter_add`` function, using the Python iterator protocol:import numpy as np
✓def iter_add_py(x, y, out=None): addop = np.add it = np.nditer([x, y, out], [], [['readonly'], ['readonly'], ['writeonly','allocate']]) with it: for (a, b, c) in it: addop(a, b, out=c) return it.operands[2]✓
def iter_add(x, y, out=None): addop = np.add it = np.nditer([x, y, out], [], [['readonly'], ['readonly'], ['writeonly','allocate']]) with it: while not it.finished: addop(it[0], it[1], out=it[2]) it.iternext() return it.operands[2]✓
def outer_it(x, y, out=None): mulop = np.multiply it = np.nditer([x, y, out], ['external_loop'], [['readonly'], ['readonly'], ['writeonly', 'allocate']], op_axes=[list(range(x.ndim)) + [-1] * y.ndim, [-1] * x.ndim + list(range(y.ndim)), None]) with it: 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)✓
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)
✗a = np.arange(6, dtype='i4')[::-2] with np.nditer(a, [], [['writeonly', 'updateifcopy']], casting='unsafe', op_dtypes=[np.dtype('f4')]) as i: x = i.operands[0] x[:] = [-1, -2, -3] # a still unchanged here a, x✓
Aliases
-
numpy.nditer