What is the numpy.eye() function in Python?
Overview
The numpy.eye() function in Python is used to return a two-dimensional array with ones (1) on the diagonal and zeros (0) elsewhere.
Syntax
numpy.eye(N, M=None, k=0, dtype=<class 'float'>, order='C', *, like=None)
Parameters
The numpy.eye() function takes the following parameter values:
N: This represents the number of rows we want in the output array.M: This represents the number of columns we want in the output array. This is optional.k: This represents the index of the diagonal.0is the default value and the main diagonal. This is optional.dtype: This represents the data type of array to be returned. This is optional.order: This represents whether the output should be stored inCorForder in memory. This is optional.like: This is the array prototype orarray_likeobject.
Return value
The numpy.eye() function returns a type of array where all the elements are equal to 0, except for the diagonal, whose values are equal to 1.
Example 1
import numpy as np# An array with 3 rows with with the ones starting at the index i.e fron the second columnmyarray = np.eye(3, k=1)print(myarray)
Explanation
- Line 1: We import the
numpymodule. - Line 4: We use the
numpy.eye()function to create an array with3rows and the ones should start on index1of the array. The output is stored in a variablemyarray. - Line 6: We print the variable
myarray.
Example 2
import numpy as np# An array with 2 rows and integer data typemyarray = np.eye(2, dtype=int)print(myarray)
Explanation
- Line 1: We import the
numpymodule. - Line 4: We use the
numpy.eye()function to create an array with2rows. The data type of the array should be integer. The output is stored in a variablemyarray. - Line 6: We print the variable
myarray.