Contents
Python Numpy – zeros(shape)
To create a numpy array with zeros, given shape of the array, use numpy.zeros() function.
The syntax to create zeros numpy array is:
numpy.zeros(shape, dtype=float, order='C')
where
shape
could be an int for 1D array and tuple of ints for N-D array.- dtype is the datatype of elements the array stores. By default, the elements are considered of type float. You may specify a datatype.
C
andF
are allowed values fororder
. This effects only how the data is stored in memory. C: C-style of storing multi-dimensional data in row-major memory. F: Fortran style of storing multi-dimensional data in column-major in memory.
Mostly, we only use shape
parameter.
Example 1: Python Numpy Zeros Array – One Dimensional
To create a one-dimensional array of zeros, pass the number of elements as the value to shape
parameter.
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 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.
Example 2: Python Numpy Zeros Array – Two Dimensional
To create a two-dimensional array of zeros, pass the shape i.e., number of rows and columns as the value to shape
parameter.
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 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.
Example 3: Python Numpy Zeros Array – Three Dimensional
To create a three-dimensional array of zeros, pass the shape as tuple to shape
parameter.
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 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.
Example 4: Python 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 Output
[0 0 0 0 0 0 0 0]
Summary
In this article of Python Examples, we created numpy array of specific shape and datatype and initialized the array with zeros.