BetterDocs
Home
Docs

Creation | np.eye()

Method:

np.eye(N, M=None, k=0, dtype=np.float64, order='C', *, device=None, like=None)

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

Returns:

np.ndarray

Parameters:

N: int-

Number of rows for the NumPy array.

import numpy as np

# 3x3 identity matrix
identity_matrix = np.eye(N=3)
print(identity_matrix)
'''
Output:
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
'''

If N=0, an empty array is returned.

M: int, Optional-

Number of columns for the NumPy array (defaults to N if None).

import numpy as np

# 3x2 identity matrix
identity_matrix = np.eye(3, M=2)
print(identity_matrix)
'''
Output:
[[1. 0.]
 [0. 1.]
 [0. 0.]]
'''

If N or M is set to 0, an empty array is returned.

k: int, Optional-

Index of the diagonal of ones.

k = 0 (default) +

k = 1 +

k = -1 +

When k=0, the ones diagonal is placed at index [0,0].

When k>0, the ones diagonal shifts by k indexes towards the right.

When k<0, the ones diagonal shifts by k indexes towards the left.

dtype: np.float64, Optional-

The desired data-type for the NumPy array.

import numpy as np

# 3x3 identity matrix
identity_matrix = np.eye(3, dtype=np.int32)
print(identity_matrix)
'''
Output:
[[1 0 0]
 [0 1 0]
 [0 0 1]]
'''

Values: +

By passing the dtype, you are implicitly converting the values to the passed dtype.

order: {'C', 'F'}, Optional-

Specifies the memory layout order for multi-dimensional arrays.

order = C (default) +

order = F +

.ravel()  is a NumPy function used to flatten a multi-dimensional array into a 1D array.

device: None, Optional-

In NumPy 2.1, the device parameter in np.eye() is still in an early stage and currently only accepts "cpu" as a valid option. At this time, it is primarily there for future development, allowing the function to eventually support GPUs or other devices, but for now, it doesn't support GPU IDs directly.

like: None, Optional-

The like parameter in np.eye() was introduced to make array creation more flexible, particularly for compatibility with libraries that extend NumPy, like Dask, CuPy, or other libraries that create arrays compatible with np.ndarray but optimized for different backends (e.g., parallel processing or GPU-based arrays).


Logo

BetterDocs

Support

EmailDiscordForms

Documentations

Python

Company

AboutDocs

Policies

Terms of ServicePrivacy Policy