NumPy eye()

The eye() method creates a 2D array with 1s on the diagonal and 0s elsewhere.


eye() Syntax

The syntax of eye() is:

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

Note: Here, M = None implies that M = N by default.


eye() Arguments

The eye() method takes the following arguments:

  • N- Number of rows in the output (can be int)
  • M (optional)- Number of columns in the output (can be int)
  • k (optional) - the diagonal in question(can be int)
  • dtype (optional) - the datatype of the resultant array
  • order (optional) - the memory layout of the array (can be 'C' or 'F')

Notes:

  • By default k = 0 and represents the main diagonal.
    • k > 0 represents diagonals above the main diagonal
    • k < 0 represents diagonals below the main diagonal.

eye() Return Value

The eye() method returns the resultant array with shape NxM with all elements as 0 except the kth diagonal where all elements are 1.


Example 1: Create a Square Array Using eye()

Output

2x2 square array
 [[1. 0.]
 [0. 1.]]
2x2 square array with k = 1
 [[0. 1.]
 [0. 0.]]
2x2 square array with k = -1
 [[0. 0.]
 [1. 0.]]

Example 2: Create a Non-Square Array Using eye()

If we pass both N and M as arguments, a non-square array is created.

Let us see an example.

Output

2x3  array
[[1. 0. 0.]
 [0. 1. 0.]]
3x2  array
 [[1. 0.]
 [0. 1.]
 [0. 0.]]

Example 3: Using the Optional dtype Argument With eye()

The optional dtype argument specifies the data type of the created array.

Let's see an example.

Output

2x2 float  array
[[1. 0.]
 [0. 1.]]
2x2 int  array
 [[1 0]
 [0 1]]
2x2 string  array
 [['1' '']
 ['' '1']]

Note: When the array is converted to a string array, the 0s are replaced by empty strings.


Using the Optional order Argument With eye

With eye(), there are two possible options for order argument.

  • 'C': C stands for C style order where the array is filled row-wise.
  • 'F': F stands for Fortran-style order where the array is filled column-wise.