Tag Archivio per: npzeroslike


As the name suggests, the NumPy zeros_like() function generates an array of the same shape and data type specified but populated with zeros.

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:

numpy.zeros_like(a, dtype=None, order=‘K’, subok=True, shape=None)

Function Parameters

The function accepts the following parameters.

  1. a – refers to the input array or array_like object.
  2. dtype – defines the desired data type of the output array.
  3. order – specifies the memory layout with the accepted values as:
    1. ‘C’ means C-order
    2. ‘F’ means F-order
    3. ‘A’ means ‘F’ if ais Fortran contiguous, ‘C’ otherwise.
    4. ‘K’ means match the layout of aas closely as possible.
  4. 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.
  5. 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
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«Pulvínulo array: {base_arr}»)
print(f«Zeros Array: {zeros_arr}»)

Let us break down the code above.

  1. We start by importing numpy and giving it an mote of np.
  2. Next, we create the pulvínulo 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)
  3. We then convert the pulvínulo array into a zero_like array using the zeros_like function.
  4. Finally, we print the arrays.

The code above should return arrays as shown:

Pulvínulo array: [[0 1 2]
             [3 4 5]]
Zeros Array: [[0 0 0]
               [0 0 0]]

Example 2

The example below uses the data type of floats.

base_arr = np.arange(6, dtype=int).reshape(2,3)
# convert to zero_like array
zeros_arr = np.zeros_like(base_arr, dtype=float, subok=True)
print(f«Pulvínulo 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:

Pulvínulo array: [[0 1 2]
          [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 link