There are many functions provided by the numpy. The numpy ones_like is one of them. If you want to create numpy array of same same and type from existing array then this function is for you. It will fill all elements of numpy array as one. In this tutorial you will learn how to implement the numpy.ones_like function in steps.
Syntax of the numpy.ones_like Function
numpy.ones_like(a, dtype=None, order='K', subok=True, shape=None)
a: This is the input array whose shape and data type will be used to create the new array filled with ones.
dtype (optional): This is the data type of the output array. It can be specified, and if not provided, the data type of the input array (a) will be used.
order (optional): Specifies the memory layout of the output array. It can be ‘C’ for C-style (row-major) or ‘F’ for Fortran-style (column-major). The default is ‘K’, which means it tries to keep the order of the input array.
subok (optional): If True, the subclass of the input array will be preserved. The default is True.
shape (optional): If provided, it overrides the shape of the input array. The output array will have this shape.
Steps to Implement numpy.ones_like Function
Lets implement the numpy.ones_like function in steps.
Step 1: Import the required package NumPy
First make sure to import the NumPy library at the beginning of your script or notebook. You can imort numpy using the import statement.
import numpy as np
Step 2: Create an Array
You need an existing array that will be used as a template for shape and data type. You can create numpy array using the np.array() function.
original_array = np.array([[10, 20, 30], [40, 50, 60]])
Step 3: Use numpy.ones_like
Apply the numpy.ones_like function to create a new array with the same shape and data type as the original array, but filled with ones.
ones_array = np.ones_like(original_array)
Output
array([[1, 1, 1],
[1, 1, 1]])
Here, ones_array
has the same shape as original_array
but is filled with ones.
Full Code
import numpy as np
# Step 2: Create an Array
original_array = np.array([[10, 20, 30], [40, 50, 60]])
# Step 3: Use numpy.ones_like
ones_array = np.ones_like(original_array)
# Print the result
print("Original Array:")
print(original_array)
print("\nArray of Ones:")
print(ones_array)
Output
Original Array:
[[10 20 30]
[40 50 60]]
Array of Ones:
[[1 1 1]
[1 1 1]]
Now, ones_array
has the same shape as original_array
but is filled with ones.
Conclusion
There are many ways to create numpy array. In this tutorial you have learned how to use the np.ones_like() to create same shape and type of existing array filled with ones. The above steps is very simple to impelement.
Leave a Reply