NumPy Tutorial NumPy Statistics NumPy References

NumPy - eye() function



The NumPy eye() function returns a 2-D array with ones on the diagonal and zeros elsewhere.

Syntax

numpy.eye(N, M=None, k=0, dtype='float', order='C')

Parameters

N Required. Specify number of rows in the output.
M Optional. Specify number of columns in the output. Default is N.
k Optional. Specify index of the diagonal. 0 refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.
dtype Optional. Specify the desired data-type for the output. Default: float.
order Optional. Specify whether to store the result. Two possible values are: C (C-style) and F (Fortran-style). Default: 'C'

Return Value

Returns a 2-D array with ones on the diagonal and zeros elsewhere.

Example:

In the example below, eye() function is used to create 2-D array using different available parameters.

import numpy as np

#using default parameters
Arr1 = np.eye(N=3)
print("Arr1 is:\n", Arr1)

#using positive k
Arr2 = np.eye(N=3, M=4, k=1)
print("\nArr2 is:\n", Arr2)

#using negative k with int data type
Arr3 = np.eye(N=3, M=4, k=-1, dtype=int)
print("\nArr3 is:\n", Arr3)

The output of the above code will be:

Arr1 is:
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

Arr2 is:
[[0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]

Arr3 is:
 [[0 0 0 0]
  [1 0 0 0]
  [0 1 0 0]]

❮ NumPy - Functions