What is the numpy.ma.ones_like() function in NumPy?
Overview
In NumPy, the ma.ones_like() function is used to return an array of ones, 1, with the same shape as a given array.
Syntax
The syntax for the ma.ones_like() function is given below:
ma.ones_like(a, dtype=None, order='K')
Syntax for the ma.ones_like() function in NumPy
Parameter value
The ma.ones_like() function takes the following parameter values:
a: This represents thearray_likeobject or the prototype.dtype: This represents the data type of the result. This parameter is optional.order: This represents the type of order of the memory layout of the result. This is an optional parameter.
Return value
The ma.ones_like() function returns an array of ones, 1, with the same shape and types as the array_like that is passed to it.
Example
import numpy as np# creating an array_likethisarray = np.arange(4, dtype = int)# implementing the numpy.ones_like() functionmyarray = np.ones_like(thisarray)# printing the two arraysprint(thisarray)print(myarray)
Explanation
- Line 1: We import the
NumPymodule. - Line 4: We create an array prototype using the
numpy.arange()method. We assign the output to a variable calledthisarray. - Line 7: We implement the
ma.ones_like()function onthisarrayand assign the result to another variable calledmyarray. - Lines 11–12: We print both the prototype
thisarrayand the modified arraymyarray.