Numpy zeros()
is also known as np.zeros or numpy.zeros. It is used to create a Numpy array whose each element has a value of zero. Using array()
function, you can also create Numpy array whose each element is having a value of zero. Then why do we need to use zeros()
function? Let's understand it with the help of a simple example:
Suppose, you want to create a Numpy array having 3 rows and 15 columns, and each element's value is zero. With array()
function, you can do it like this:
import numpy as np np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
As you can see this way of creating an array is a messy task and at the same time, it is error-prone. With zeros() function, this task can be achieved very easily. Let's look at it how:
np.zeros(shape=(3, 15), dtype=int)
As you can see how simple it is to create array with zeros() function.
Finally, lets take a look at the syntax of numpy zeros()
function
np.zeros(shape, dtype=None) OR numpy.zeros(shape, dtype=None)
shape
parameter is used to specify the dimensions of the Numpy array. Here, you specify the value in the form of tuple or list.
dtype
is used to specify the data type of array and this parameter is optional.
Let's create a one-dimensional array with zeros() function.
import numpy as np a = np.zeros(6) print(a)
Output of the above program
[0. 0. 0. 0. 0. 0.]
Python program to create numpy zeros array with the specified data type
import numpy as np a = np.zeros(6, dtype=int) print(a)
Output of the above program
[0 0 0 0 0 0]
Python program to create numpy zeros array with the specific dimension or shape
import numpy as np a = np.zeros(shape=(2, 6), dtype=int) print(a) b = np.zeros((2, 6), dtype=int) print(b) c = np.zeros([2, 6], dtype=int) print(c)
Output of the above program
[[0 0 0 0 0 0] [0 0 0 0 0 0]] [[0 0 0 0 0 0] [0 0 0 0 0 0]] [[0 0 0 0 0 0] [0 0 0 0 0 0]]
As you can see there are three different ways of specifying shape to Numpy zeros() function.