The numpy.zeros_like()
function in Python is used to return an array of zeros (0
) with the same shape and data type as the array passed to it.
numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None)
The numpy.zeros_like()
function takes the following parameter values:
a
: This represents the array_like
object.dtype
: This represents the desired data type of the array. This is optional.order
: This overrides the memory layout of the result. It can take any of C
, F
, A
, or K
orders. This is optional.subok
: This takes a boolean value. If the value passed is True
, then the newly created array will make use of the subclass type of the array_like
object. Otherwise, it will make use of the base-class array. The default value is True
. This is optional.shape
: This represents integers or sequence of integers that helps override the shape of the output array.The numpy.zeros_like()
function returns an array of zeros (0
) with the same shape and type as the array_like
object passed to it.
import numpy as np# creating an array_likethisarray = np.arange(5, dtype = int)# implementing the numpy.zerps_like() functionmyarray = np.zeros_like(thisarray, dtype=int, order='C', subok=True, shape=(2,3))# printing the two arraysprint(thisarray)print(myarray)
Line 1: We import the numpy
module.
Line 4: We create an array prototype with 5
elements using the numpy.arange()
method. The output is assigned to a variable thisarray
.
Line 7: We implement the numpy.zero_like()
function on thisarray
to create an array with the int
data type, C
order, True
value for subok
and a shape of 2
arrays with 3
elements each. The result is assigned to another variable myarray
.
Line 11–12: We print both the prototype thisarray
and the modified array myarray
.