Skip to main content
How To Use Numpy np.zeros() Function

How To Use Numpy np.zeros() Function

The method np.zeros() returns an array of comparable structure and size with the values of the array’s elements set to zeros. The NumPy zeros method enables you to create Numpy arrays that contain only zeros. The zeros() function is used to get a new array of a given shape and type filled with zeros.

The zeros() function accepts three arguments and returns a zero-valued array.

Numpy

Numpy is a Python third-party library that supports massive multidimensional arrays and matrices, as well as a collection of mathematical functions to operate on them. The numpy library’s fundamental data structure is the numpy array.

Syntax:

numpy.zeros(shape, dtype = None, order = 'C')

Parameters :

shape: integer or sequence of integers number
dtype: The second parameter is optional and is the datatype of the returning array. If you don’t define the data type, then np.zeros() will use float data type by default.
order : C_contiguous or F_contiguous
C-contiguous order in memory(last index varies the fastest)
C order means that operating row-rise on the array will be slightly quicker
FORTRAN-contiguous order in memory (first index varies the fastest).
F order means that column-wise operations will be faster.

Returns :

The array of zeros having given shape, order and datatype.

import numpy as np

b = np.zeros(2, dtype = int)
print("Matrix b : \n", b)

a = np.zeros([2, 2], dtype = int)
print("\nMatrix a : \n", a)

c = np.zeros([3, 3])
print("\nMatrix c : \n", c)

Output:

Matrix b : 
 [0 0]

Matrix a : 
 [[0 0]
 [0 0]]

Matrix c : 
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]

Create a 4×4 matrix Using zeros() function

Let’s create a 4×4 matrix and apply the function of a zero.

import numpy as np

a = np.zeros([4, 4], dtype=int)
print("Matrix a : \n", a)

Output :

Matrix a :
 [[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]

Leave a Reply

Your email address will not be published. Required fields are marked *