The ones_like() function is defined under numpy, imported as import numpy as np. We can create multidimensional arrays and derive other mathematical statistics with the help of numpy.
np.ones_like
The np.ones_likes() function returns the array of ones with the same shape and type as the given array. The np.ones_like() method accepts four parameters, and it is used to return the array of similar shape and size with values of elements of array replaced with ones. The shape and data type define these same attributes of the returned array.
Syntax
numpy.ones_like(array,dtype,order,subok)
Parameters
It takes four parameters, out of which two parameters are optional.
The first parameter is the input array.
The second parameter is the subok parameter, which is optional; it takes Boolean values, and if it is true, the newly created array will be a sub-class of the main array, and if it is false, it will be a base-class array.
The third parameter is the order, which represents the order in the memory. The fourth parameter is dtype, which is optional and, by default, has the value float. It is the data type of the returned array.
Return Value
It returns an array with element values as ones.
Programs on ones_like() method in Python
Write a program to show the working of the ones_like() function in Python.
# app.py import numpy as np arr2 = np.arange(16, dtype=float).reshape(4, 4) print("\n\narr2 before full_like : \n", arr2) # using full_like print("\narr2 after full_like : \n", np.full_like(arr2, -3))
Output
python3 app.py arr2 before full_like : [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 8. 9. 10. 11.] [12. 13. 14. 15.]] arr2 after full_like : [[-3. -3. -3. -3.] [-3. -3. -3. -3.] [-3. -3. -3. -3.] [-3. -3. -3. -3.]]
In this example, we can see that we have preserved the array’s size and shape and created a new array with all the values as a 4×4 matrix.
Write a program to take a 2×2 matrix and apply the ones_like() function.
# app.py import numpy as np arr1 = np.arange(4).reshape(2, 2) print("Original array : \n", arr1) arr2 = np.ones_like(arr1, float) print("\nMatrix arr2 : \n", arr2)
Output
python3 app.py Original array : [[0 1] [2 3]] Matrix arr2 : [[1. 1.] [1. 1.]]
In this example, we can see that when we took a 2×2 array with values 0,1,2,3, a new array is constructed with the same shape and size with value all values as one.