Using NumPy’s zeros_like() function (4 examples)

Updated: February 28, 2024 By: Guest Contributor Post a comment

Overview

NumPy is a fundamental library for scientific computing in Python. It provides a high-performance multidimensional array object and tools for working with these arrays. Among its numerous array creation functions, NumPy’s zeros_like() function stands out for its utility in creating arrays of zeros with the same shape and type as a given array. This tutorial delves into the usage of zeros_like() function with four progressively advanced examples.

Prerequisites:

  • Basic understanding of Python
  • NumPy library (To install NumPy, you can use pip install numpy)

Syntax & Parameters

Syntax;

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

Parameters:

  • a: array_like. The shape and data-type of a define these same attributes of the returned array.
  • dtype: data-type, optional. Overrides the data type of the result.
  • order: {‘C’, ‘F’, ‘A’, or ‘K’}, optional. Overrides the memory layout of the result. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible.
  • subok: bool, optional. If True, then the newly created array will use the sub-class type of a, otherwise it will be a base-class array. Defaults to True.
  • shape: int or sequence of ints, optional. Overrides the shape of the result. If shape is not specified, the shape of a is used.

Returns:

  • out: ndarray. Array of zeros with the same shape and type as a, unless overridden with the dtype or shape parameters.

Example 1: Basic Usage of zeros_like()

Starting with the basics, zeros_like() can create a new array filled with zeros, exactly mirroring the structure of a provided array. Here’s a straightforward example:

import numpy as np

# Original array of integers
a = np.array([[1, 2, 3], [4, 5, 6]])

# Creating an array of zeros with the same shape as 'a'
b = np.zeros_like(a)
print(b)

The output:

[[0 0 0]
 [0 0 0]]

This basic example illustrates how to quickly initialize an array that matches the dimensions of an existing array, effectively setting the stage for further manipulations or data initializations.

Example 2: Preserving Data Type

The function’s ability to preserve the type of the original array while creating a new one of zeros is crucial, especially when working with arrays that aren’t of the default floating-point type. Here’s how it works:

import numpy as np

# Original array of floats
a = np.array([[1.5, 2.5], [3.5, 4.5]], dtype=np.float64)

# Creating an array of zeros with the same type and shape
b = np.zeros_like(a)
print(b)

The output:

[[0. 0.]
 [0. 0.]]

Note the zeros are of type float, just like the original array. This feature ensures compatibility and reduces the risk of type-related errors in further computations.

Example 3: Specifying the Data Type

While the zeros_like() function usually preserves the data type of the original array, NumPy also allows for the specification of a different type for the new array. This flexibility can be particularly useful in scenarios where memory efficiency or computational requirements demand a different type. Here’s how to specify a different data type:

import numpy as np

# Original array
a = np.array([[1, 2], [3, 4]])

# Creating an array of zeros with the same shape but different type
b = np.zeros_like(a, dtype=np.float64)
print(b)

The output:

[[0. 0.]
 [0. 0.]]

In this example, even though the original array contains integers, the new array of zeros is created with type float64. This modification showcases the flexibility and control NumPy offers for array management and data processing.

Example 4: Advanced Use: Customizing Layout

NumPy’s zeros_like() offers an additional feature to control the memory layout of the created array. The options are ‘C’ for C-style row-major order, ‘F’ for Fortran-style column-major order, or ‘A’ to preserve the original array’s layout. This customization can affect the performance of subsequent operations on the array. Let’s see an example of how to create a zeros array with a specific memory layout:

import numpy as np

# Original array
a = np.array([[1, 2], [3, 4]], order='F')

# Creating a zeros-like array with 'C' layout despite the original's 'F' layout
b = np.zeros_like(a, order='C')
print(b)
print('Layout of b:', np.isfortran(b))

The output:

[[0 0]
 [0 0]]
Layout of b: False

This result indicates that unlike the original array a, which was in Fortran-style layout, the new array b is in the C-style row-major order. This level of control is particularly useful in optimizing performance for specific computing tasks.

Conclusion

NumPy’s zeros_like() function is powerful and versatile, perfect for creating zero-filled arrays that match the shape and type of existing arrays. By examining four examples, ranging from basic to advanced, this tutorial has demonstrated the function’s utility in initializing arrays, preserving or specifying data types, and customizing array layouts. Understanding these capabilities allows for more efficient and effective array manipulations within the NumPy ecosystem.