numpy.nditer¶

class numpy.nditer[源代码]

Efficient multi-dimensional iterator object to iterate over arrays. To get started using this object, see the introductory guide to array iteration.

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 iterator’s coordinates or index, use the C-style 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):
it = np.nditer([x, y, out], [],
with it:
for (a, b, c) in it:
return it.operands

Here is the same function, but following the C-style pattern:

def iter_add(x, y, out=None):

it = np.nditer([x, y, out], [],
with it:
while not it.finished:
it.iternext()

return it.operands

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'],
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

>>> 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'],
order=kwargs.get('order','K'),
casting=kwargs.get('casting','safe'),
buffersize=kwargs.get('buffersize',0))
while not it.finished:
it = lamdaexpr(*it[1:])
it.iternext()
return it.operands

>>> 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])

If operand flags “writeonly” or “readwrite” are used the operands may be views into the original data with the WRITEBACKIFCOPY flag. In this case nditer must be used as a context manager or the nditer.close method must be called before using the result. The temporary data will be written back to the original data when the __exit__ function is called but not before:

>>> a = np.arange(6, dtype='i4')[::-2]
>>> with nditer(a, [],
...        [['writeonly', 'updateifcopy']],
...        casting='unsafe',
...        op_dtypes=[np.dtype('f4')]) as i:
...    x = i.operands
...    x[:] = [-1, -2, -3]
...    # a still unchanged here
>>> a, x
array([-1, -2, -3]), array([-1, -2, -3])

It is important to note that once the iterator is exited, dangling references (like x in the example) may or may not share data with the original data a. If writeback semantics were active, i.e. if x.base.flags.writebackifcopy is True, then exiting the iterator will sever the connection between x and a, writing to x will no longer write to a. If writeback semantics are not active, then x.data will still point at some part of a.data, and writing to one will affect the other.

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 : 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. Valid only before the iterator is closed. 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) operands[Slice] 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.

Methods

 close() Resolve all writeback semantics in writeable operands. 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 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.