Create Array with Zeros in NumPy

NumPy – Array with zeros

To create a numpy array with all zeros, of specific dimensions or shape, use numpy.zeros() function.

Syntax

The syntax to create zeros numpy array is

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

where

Mostly, we only use shape parameter.

Examples

1. One dimensional array with zeros

To create a one-dimensional array of zeros, pass the number of elements for shape parameter to numpy.zeros() function.

In this example, we shall create a numpy array with 8 zeros.

Python Program

import numpy as np

# Create numpy array with zeros
a = np.zeros(8)

# Print numpy array
print(a)
Run Code

Output

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

Numpy array (1-Dimensional) of size 8 is created with zeros. The default datatype is float.

2. Two dimensional array with zeros

To create a two-dimensional array of zeros, pass the shape i.e., number of rows and columns as a tuple for shape parameter to numpy.zeros() function.

In this example, we shall create a numpy array with 3 rows and 4 columns.

Python Program

import numpy as np

# Create 2D numpy array with zeros
a = np.zeros((3, 4))

# Print numpy array
print(a)
Run Code

Please observe that we have provided the shape as a tuple of integers.

Output

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

Numpy array (2-Dimensional) of shape (3,4) is created with zeros. The default datatype is float.

3. Three dimensional numpy array with zeros

To create a three-dimensional array of zeros, pass the shape as tuple for shape parameter to numpy.zeros() function.

In this example, we shall create a numpy array with shape (3,2,4).

Python Program

import numpy as np

# Create 3D numpy array with zeros
a = np.zeros((3, 2, 4))

# Print numpy array
print(a)
Run Code

Please observe that we have provided the shape as a tuple of integers.

Output

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

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

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

Numpy array (3-Dimensional) of shape (3,2,4) is created with zeros. The default datatype is float.

4. NumPy zeros array with specific datatype

To create numpy zeros array with specific datatype, pass the required datatype as dtype parameter.

In this example, we shall create a numpy array with zeros of datatype integers.

Python Program

import numpy as np

# Create numpy array with zeros of integer datatype
a = np.zeros(8, int)

# Print numpy array
print(a)
Run Code

Output

[0 0 0 0 0 0 0 0]

Summary

In this NumPy Tutorial, we created numpy array of specific shape and datatype and initialized the array with zeros.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us