Today we’ll learn how to create an array filled with ones, zeros or arbitrary data.
Sometimes you may want to create an array filled with ones or zeros. There are two methods that you can use to achieve that: ones and zeros. Here’s how they work:
The ones method creates an array filled with ones. It takes the shape of the array as an argument:
>>> a = np.ones((3, 6))
>>> print(a)
[[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1. 1.]]
The zeros method works in a similar way, but it fills the array with zeros:
>>> b = np.zeros((3, 6))
>>> print(b)
[[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0.]]
For 1-dimensional arrays you can pass the shape as a 1-tuple:
>>> c = np.zeros((5,))
>>> print(c)
[0. 0. 0. 0. 0.]
or an integer:
>>> d = np.zeros(5)
>>> print(d)
[0. 0. 0. 0. 0.]
By default the ones and zeros are float numbers. If you want them to be a different type, you can pass the dtype argument set to the type of your choice. Suppose we need integers. We can do it this way:
>>> e = np.ones((3, 6), dtype = int)
>>> print(e)
[[1 1 1 1 1 1]
[1 1 1 1 1 1]
[1 1 1 1 1 1]]
or this way:
>>> f = np.zeros((2, 4, 3), dtype = np.int8)
>>> print(f)
[[[0 0 0]
[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]
[0 0 0]]]
There are two other methods that you can use to create arrays filled with ones or zeros, ones_like and zeros_like. They take an existing array as an argument and create a new array of the same shape. Here’s how they work. First the ones_like method:
>>> h = np.array([[3.2, 4.6, 6.4], [4.7, 7.9, 5.3]])
>>> i = np.ones_like(h)
>>> print(i)
[[1. 1. 1.]
[1. 1. 1.]]
And now the zeros_like method:
>>> j = np.zeros_like(h, dtype = int)
>>> print(j)
[[0 0 0]
[0 0 0]]
There is one more method that works in a similar way, empty. It should be used with caution. It returns an uninitialized array, so an array with arbitrary data of the given shape and type that must be initialized later on. Here’s an example:
>>> g = np.empty((5, 2))
>>> print(g)
[[6.23042070e-307 1.24610383e-306]
[6.89804132e-307 8.45610231e-307]
[9.34601642e-307 7.56587584e-307]
[8.45559303e-307 1.06811422e-306]
[1.05694828e-307 2.22522596e-306]]
Here’s the video version: