Numpy.zeros() Method in Python

Numpy.zeros() method “returns a new array of given shape and type, with zeros.”

Syntax

numpy.zeros(shape, dtype, order) 

Parameters

  1. shape: The first parameter is the shape, an integer, or a sequence of integers.
  2. dtype: The second parameter is optional and is the datatype of the returning array. If you don’t define the data type, np.zeros() will use float data type by default.
  3. order: The third parameter is an order, representing the order in the memory, such as C_contiguous or F_contiguous.

Return Value

The np.zeros() method returns an array with element values as zeros.

Example 1: How to Use numpy.zeros() method

import numpy as np

print(np.array([[0, 0, 0], [0, 0, 0]]))

Output

[[0 0 0]
 [0 0 0]]

Example 2: Passing dtype argument

import numpy as np

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

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

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

Output

Matrix arr1 :
 [0 0 0 0]

Matrix arr2 :
 [[0 0]
 [0 0]]

Matrix arr3 :
 [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Example 3: Passing a shape argument

We can create arrays with a particular shape. We can do this by specifying the shape parameter.

import numpy as np

print(np.zeros(shape=(2, 3)))

Output

[[0. 0. 0.]
 [0. 0. 0.]]

Technically, you don’t have to call out the shape = parameter explicitly; you can define the shape with a tuple of values. Python will infer that it refers to shape (i.e., the shape is a “positional argument“).

import numpy as np

print(np.zeros((2, 3)))

Output

[[0. 0. 0.]
 [0. 0. 0.]]

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.