class numpy.nditer
[source]
Efficient multi-dimensional iterator object to iterate over arrays. To get started using this object, see the introductory guide to array iteration.
Parameters: |
op : ndarray or sequence of array_like The array(s) to iterate over. flags : sequence of str, optional Flags to control the behavior of the iterator.
op_flags : list of list of str, optional This is a list of flags for each operand. At minimum, one of “readonly”, “readwrite”, or “writeonly” must be specified.
op_dtypes : dtype or tuple of dtype(s), optional The 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’}, optional Controls 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 “allocate” operands, as they are allocated to be compatible with iteration order. Default is ‘K’. casting : {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional Controls 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.
op_axes : list of list of ints, optional If 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, optional The desired shape of the iterator. This allows “allocate” operands 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, optional When buffering is enabled, controls the size of the temporary buffers. Set to 0 for the default value. |
---|
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 iterator’s coordinates or index, use the C-style pattern.
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 C-style 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])
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. |
finished | (bool) Whether the iteration over the operands is finished or not. |
has_delayed_bufalloc | (bool) If True, the iterator was created with the “delay_bufalloc” flag, and no reset() function was called on it yet. |
has_index | (bool) If True, the iterator was created with either the “c_index” or the “f_index” flag, and the property index can be used to retrieve it. |
has_multi_index | (bool) If True, the iterator was created with the “multi_index” flag, and the property multi_index can be used to retrieve it. |
index | When the “c_index” or “f_index” flag was used, this property provides access to the index. Raises a ValueError if accessed and has_index is False. |
iterationneedsapi | (bool) Whether iteration requires access to the Python API, for example if one of the operands is an object array. |
iterindex | (int) An index which matches the order of iteration. |
itersize | (int) Size of the iterator. |
itviews | Structured view(s) of operands in memory, matching the reordered and optimized iterator access pattern. |
multi_index | When the “multi_index” flag was used, this property provides access to the index. Raises a ValueError if accessed accessed and has_multi_index is False. |
ndim | (int) The iterator’s dimension. |
nop | (int) The number of iterator operands. |
operands | (tuple of operand(s)) The array(s) to be iterated over. |
shape | (tuple of ints) Shape tuple, the shape of the iterator. |
value | Value of operands at current iteration. Normally, this is a tuple of array scalars, but if the flag “external_loop” is used, it is a tuple of one dimensional arrays. |
copy () | Get a copy of the iterator in its current state. |
debug_print () | Print the current state of the nditer instance and debug info to stdout. |
enable_external_loop () | When the “external_loop” was not used during construction, but is desired, this modifies the iterator to behave as if the flag was specified. |
iternext () | Check whether iterations are left, and perform a single internal iteration without returning the result. |
next | x.next() -> the next value, or raise StopIteration |
remove_axis (i) | Removes axis i from the iterator. |
remove_multi_index () | When the “multi_index” flag was specified, this removes it, allowing the internal iteration structure to be optimized further. |
reset () | Reset the iterator to its initial state. |
© 2008–2017 NumPy Developers
Licensed under the NumPy License.
https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.nditer.html