NumPy np.zeros_like()
Using this guide, we will discuss this function, its syntax, and how to use it with practical examples.
Function Syntax
The function provides a relatively simple syntax as shown below:
Function Parameters
The function accepts the following parameters.
- a – refers to the input array or array_like object.
- dtype – defines the desired data type of the output array.
- order – specifies the memory layout with the accepted values as:
- ‘C’ means C-order
- ‘F’ means F-order
- ‘A’ means ‘F’ if ais Fortran contiguous, ‘C’ otherwise.
- ‘K’ means match the layout of aas closely as possible.
- subok – if True, the new array uses the subclass type of the input array or array_like object. If this value is set to false, use the base-class array. By default, this value is set to True.
- shape – overwrites the shape of the output array.
Function Return Value
The function returns an array filled with zeros. The output array takes the same shape and data type as the input array.
Example
Take a look at the example code shown below:
import numpy as np
# create an array shape and data type
base_arr = np.arange(6, dtype=int).reshape(2,3)
# convert to zero_like array
zeros_arr = np.zeros_like(base_arr, dtype=int, subok=True)
print(f"Base array: {base_arr}")
print(f"Zeros Array: {zeros_arr}")
Let us break down the code above.
- We start by importing numpy and giving it an alias of np.
- Next, we create the base array whose shape and data type we wish to use in the zeros_like() function. In our case, we generate an array using the arrange function and give it the shape of (2,3)
- We then convert the base array into a zero_like array using the zeros_like function.
- Finally, we print the arrays.
The code above should return arrays as shown:
[3 4 5]]
Zeros Array: [[0 0 0]
[0 0 0]]
Example 2
The example below uses the data type of floats.
# convert to zero_like array
zeros_arr = np.zeros_like(base_arr, dtype=float, subok=True)
print(f"Base array: {base_arr}")
print(f"Zeros Array: {zeros_arr}")
In the code above, we specify the dtype=float. This should return a zero_like array with floating-point values.
The output is as depicted below:
[3 4 5]]
Zeros Array: [[0. 0. 0.]
[0. 0. 0.]]
Conclusion
In this article, we covered how to use the NumPy zeros_like function. Consider altering various parameters in the examples provided to understand better how the function behaves.
Check the docs for more, and Thanks for reading!!!
Source: linuxhint.com