Create Array with Zeros in NumPy - Examples
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
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.
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)
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)
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)
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)
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.