Today we’ll learn how to create numpy identity arrays. An identity array is a square array containing ones on the main diagonal (the one going from the upper left corner to the lower right corner) and zeros elsewhere.
We use the identity function to create such an array. Have a look:
Let’s create a 5×5 square identity array:
>>> a = np.identity(5)
>>> print(a)
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
And now we want the type to be integer:
>>> b = np.identity(3, dtype = int)
>>> print(b)
[[1 0 0]
[0 1 0]
[0 0 1]]
Here’s an even shorter syntax:
>>> c = np.identity(8, int)
>>> print(c)
[[1 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0]
[0 0 0 1 0 0 0 0]
[0 0 0 0 1 0 0 0]
[0 0 0 0 0 1 0 0]
[0 0 0 0 0 0 1 0]
[0 0 0 0 0 0 0 1]]
And this is what you get if you echo the array in interactive mode:
array([[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1]])
There is another function that you can use to create an identity array. It’s the eye function. Here’s how you can use it:
In its basic form you can use it just like the identity function. This will create a square array:
>>> d = np.eye(4)
>>> print(d)
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
But the array doesn’t have to be square. You can set the number of rows and columns:
>>> e = np.eye(4, 8)
>>> print(e)
[[1. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0.]]
You can also reposition the diagonal. If you set the k argument to a positive number, the diagonal will be moved up that number of times. The default value of k is 0 – this corresponds to the main diagonal. So, let’s move the diagonal up twice:
>>> f = np.eye(4, 8, k = 2)
>>> print(f)
[[0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0.]]
If k is set to a negative number, the diagonal is moved down:
>>> g = np.eye(4, 8, k = -1)
>>> print(g)
[[0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0.]]
And now let’s move the diagonal 3 places up and change the type to int:
>>> h = np.eye(4, 8, 3, dtype = int)
>>> print(h)
[[0 0 0 1 0 0 0 0]
[0 0 0 0 1 0 0 0]
[0 0 0 0 0 1 0 0]
[0 0 0 0 0 0 1 0]]
Here’s the video version of this article: