Numpy ones_like: How to Use np ones_like() Function
Numpy ones_like() function contains four parameters and is used to return an array of the similar shape and size with values of elements of array replaced with ones. It is defined under numpy, which can be imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of numpy, which is a library in Python.
Numpy ones_likes() returns the array of ones with the same shape and type as the given array. The shape and data-type of the define these same attributes of the returned array.
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 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.
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))
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 ones which are a 4×4 matrix.
Write a program to take a 2×2 matrix and then 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)
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.