a shot of dev knowledge

RELATED TAGS

# 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. 0 is 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 in C or F order in memory. This is optional.
• like: This is the array prototype or array_like object.

### Return value

The numpy.eye() function returns a type of array where all the elements are equal to 0, except for the $k^{th}$ 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 column
myarray = np.eye(3, k=1)

print(myarray)
Implementing the numpy.eye() function

### Explanation

• Line 1: We import the numpy module.
• Line 4: We use the numpy.eye() function to create an array with 3 rows and the ones should start on index 1 of the array. The output is stored in a variable myarray.
• Line 6: We print the variable myarray.

### Example 2

import numpy as np

# An array with 2 rows and integer data type
myarray = np.eye(2, dtype=int)

print(myarray)
Implementing the numpy.eye() function

### Explanation

• Line 1: We import the numpy module.
• Line 4: We use the numpy.eye() function to create an array with 2 rows. The data type of the array should be integer. The output is stored in a variable myarray.
• Line 6: We print the variable myarray.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time