The eye()
method creates a 2D array with 1s on the diagonal and 0s elsewhere.
import numpy as np
# create a 3x3 array with 1s in diagonal and 0s elsewhere
array1 = np.eye(3)
print(array1)
'''
Output:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
'''
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 beint
)M
(optional)- Number of columns in the output (can beint
)k
(optional) - the diagonal in question(can beint
)dtype
(optional) - the datatype of the resultant arrayorder
(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 diagonalk
< 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()
import numpy as np
# create a square 2x2 array with 1s at diagonal
array1 = np.eye(2)
print('2x2 square array\n', array1)
# create a square 2x2 array with 1 above diagonal
array2 = np.eye(2, k=1)
print('2x2 square array with k = 1\n', array2)
# create a square 2x2 array with 1 below diagonal
array3 = np.eye(2, k=-1)
print('2x2 square array with k = -1\n', array3)
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.
import numpy as np
# create a 2x3 array with 1s at diagonal
array1 = np.eye(2, 3)
print('2x3 array\n', array1)
# create a 3x2 array with 1s at diagonal
array2 = np.eye(3, 2)
print('3x2 array\n', array2)
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.
import numpy as np
# create a 2x2 float array
array1 = np.eye(2, )
print('2x2 float array\n', array1)
# create a 2x2 integer array
array2 = np.eye(2, dtype = int)
print('2x2 int array\n', array2)
# create a 2x2 string array
array3 = np.eye(2, dtype = str)
print('2x2 string array\n', array3)
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.