What is the numpy.zeros_like() function in Python?
Overview
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.
Syntax
numpy.zeros_like(a, dtype=None, order='K', subok=True, shape=None)
Parameters
The numpy.zeros_like() function takes the following parameter values:
a: This represents thearray_likeobject.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 ofC,F,A, orKorders. This is optional.subok: This takes a boolean value. If the value passed isTrue, then the newly created array will make use of the subclass type of thearray_likeobject. Otherwise, it will make use of the base-class array. The default value isTrue. This is optional.shape: This represents integers or sequence of integers that helps override the shape of the output array.
Return value
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.
Example
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)
Explanation
-
Line 1: We import the
numpymodule. -
Line 4: We create an array prototype with
5elements using thenumpy.arange()method. The output is assigned to a variablethisarray. -
Line 7: We implement the
numpy.zero_like()function onthisarrayto create an array with theintdata type,Corder,Truevalue forsubokand a shape of2arrays with3elements each. The result is assigned to another variablemyarray. -
Line 11–12: We print both the prototype
thisarrayand the modified arraymyarray.