w3resource

NumPy array creation: identity() function

identity() function

The identity array is a square array with ones on the main diagonal. The identity() function return the identity array.

Syntax:

numpy.identity(n, dtype=None)
NumPy array: identity() function

Version: 1.15.0

Parameter:

Name Description Required /
Optional
n Number of rows (and columns) in n x n output. Required
dtype Data-type of the output. Defaults to float. optional

Return value:

[ndarray] n x n array with its main diagonal set to one, and all other elements 0.

Example: numpy.identity() function

>>> import numpy as np
>>> np.identity(2)
array([[ 1.,  0.],
       [ 0.,  1.]])

Pictorial Presentation:

NumPy array: identity() function

Example: numpy.identity() function

>> import numpy as np
>>> np.identity(3, dtype=int)
array([[1, 0, 0],
       [0, 1, 0],
       [0, 0, 1]])
>>> np.identity(3) #default data type is float
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

Pictorial Presentation:

NumPy array: identity() function

Python - NumPy Code Editor:

Previous: eye()
Next: ones()