w3resource

NumPy Array manipulation: ndarray.flat() function

numpy.ndarray.flat() function

The ndarray.flat() function is used to make 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in iterator object.

Syntax:

ndarray.flat
NumPy manipulation: flat() function

Version: 1.15.0

Example-1: numpy.ndarray.flat()

>>> import numpy as np
>>> a = np.arange(2, 8).reshape(3, 2)
>>> a
array([[2, 3],
       [4, 5],
       [6, 7]])
>>> a.flat[4]
6
>>> a.T
array([[2, 4, 6],
       [3, 5, 7]])
>>> a.T.flat[4]
5
>>> type(a.flat)
<class 'numpy.flatiter'>

Pictorial Presentation:

NumPy manipulation: ndarray-flat() function

Example-2: numpy.ndarray.flat()

>>> import numpy as np
>>> a = np.arange(2, 8).reshape(3, 2)
>>> a
array([[2, 3],
       [4, 5],
       [6, 7]])
>>> a.flat = 4;a
array([[4, 4],
       [4, 4],
       [4, 4]])
>>> a.flat[[2,5]] = 2; a
array([[4, 4],
       [2, 4],
       [4, 2]])

Python - NumPy Code Editor:

Previous: ravel()
Next: ndarray.flatten()