Numpy eye – Python NumPy eye() Function

NumPy eye() Function:

Numpy eye: The eye() function creates a two-dimensional array(2D) with ones on the diagonal and zeros elsewhere.

Syntax:

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

Parameters

N: This is required. It represents the number of rows in the output.

M: This is optional. It represents the number of columns in the output. If there is no value(None), it defaults to N.

k: This is optional. It represents the index of the diagonal. The main diagonal is represented by 0 (the default), an upper diagonal by a positive value, and a lower diagonal by a negative value.

dtype: This is optional. The returned array’s data type. It is float by default.

order: This is optional. It represents If the output should be stored in memory in row-major (C-style) or column-major (Fortran-style) order

Return Value:

An ndarray of shape(N, M) is returned. Except for the k-th diagonal, which has a value of one, all entries in this array are equal to zero.

NumPy eye() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword.
  • Pass some random N value as an argument to the eye() function and store it in a variable.
  • Print the above obtained first array.
  • Pass some random N, M, and positive K values as arguments to the eye() function and store it in another variable.
  • Print the above obtained second array.
  • Pass some random N, M, negative K value, and datatype as int as arguments to the eye() function and store it in another variable.
  • Print the above obtained Third array.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np

# Pass some random N value as an argument to the eye() function and 
#  Store it in a variable.
gvn_arry1 = np.eye(N=4)
# Print the above obtained first array.
print("The above obtained first array(N=3):\n", gvn_arry1)

# Pass some random N, M and positive K values as arguments to the eye() function and 
# Store it in another variable.
gvn_arry2 = np.eye(N=3, M=4, k=1)
# Print the above obtained second array.
print("The above obtained second array(N=3, M=4, k=1):\n", gvn_arry2)

# Pass some random N, M, negative K value, and datatype as int as arguments to the eye() 
# function and Store it in another variable.
gvn_arry3 = np.eye(N=3, M=4, k=-1, dtype=int)
# Print the above obtained Third array.
print("The above obtained Third array(N=3, M=4, k=-1):\n", gvn_arry3)

Output:

The above obtained first array(N=3):
[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]
The above obtained second array(N=3, M=4, k=1):
[[0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]
The above obtained Third array(N=3, M=4, k=-1):
[[0 0 0 0]
 [1 0 0 0]
 [0 1 0 0]]