Understanding numpy.empty_like() function (3 examples)

Updated: March 2, 2024 By: Guest Contributor Post a comment

Introduction

NumPy is an essential library in the Python ecosystem for numerical computing. One of its powerful functions, numpy.empty_like(), is particularly useful for creating uninitialized arrays with the same shape and data type as an existing array. This function can be a valuable tool in situations where you need to prepare an array structure without necessarily pre-popifying it with data. In this guide, we will explore the numpy.empty_like() function through a series of examples, progressively building complexity to showcase its versatility in various scenarios.

What is numpy.empty_like() Used for?

As a cornerstone of data science and numerical computing, NumPy equips Python with an array object that is both flexible and efficient. The numpy.empty_like() function is part of this offering, designed to speed up the array initialization process by sidestepping the need to fill the new array with actual numbers. This can notably reduce computation time when dealing with large datasets.

Syntax:

numpy.empty_like(prototype, dtype=None, order='K', subok=True, shape=None)

Where:

  • prototype: array_like. The shape and data-type of prototype 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 Fortran-order, ‘A’ means ‘F’ if prototype is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of prototype as closely as possible.
  • subok: bool, optional. If True, then the newly created array will use the sub-class type of prototype, otherwise it will be a base-class array. Defaults to True.
  • shape: int or tuple of ints, optional. Overrides the shape of the result. If shape is not specified, the shape of prototype is used.

Example 1: Basic Usage

First, let’s explore how to use numpy.empty_like() in its simplest form. Suppose we have an existing NumPy array, and we wish to create a new array of the same shape and data type but without initializing its values. Here is how you would do it:

import numpy as np

# Creating an existing array
existing_array = np.array([1, 2, 3, 4, 5])

# Creating an empty array like the existing one
new_array = np.empty_like(existing_array)

print(new_array)

The output of this might look something random, like:

[4607182418800017408, 4607182418800017408, 4607182418800017408, 4607182418800017408, 4607381580418769376]

Since numpy.empty_like() creates an uninitialized array, the values in new_array are essentially garbage values left in memory at those memory addresses. They could be any value, and it’s critical to remember that this function does not zero the values.

Example 2: Working with Multidimensional Arrays

Now, let’s consider a multidimensional array. The process is similar, but this example highlights numpy.empty_like()‘s ability to handle arrays of any shape.

import numpy as np

# Creating a 2D array
existing_2d_array = np.array([[1, 2, 3], [4, 5, 6]])

# Using empty_like to create a similar 2D array
new_2d_array = np.empty_like(existing_2d_array)

print(new_2d_array)

Output:

[[4607182418800017408, 4607182418800017408, 4607182418800017408],
 [4607381580418769376, 4607182418800017408, 4607585412535393744]]

Again, the actual numbers are arbitrary, serving as placeholders until they are explicitly overwritten.

Example 3: Preserving Data Type but Changing Shape

What if we want to create an empty array that has a different shape from the original but preserves the data type? Unfortunately, numpy.empty_like() alone cannot accomplish this directly, as it mimics both the shape and data type of the input array. This example, therefore, serves as a caution and suggests alternatives for achieving the intended outcome. For a different shape with the same data type, consider using numpy.empty() with manual shape specification combined with dtype attribute extraction from the existing array.

import numpy as np

# Existing array
existing_array = np.array([1, 2, 3, 4, 5])

# Desired shape
new_shape = (3, 2)

# Creating a new array with the desired shape and same data type
new_array = np.empty(new_shape, dtype=existing_array.dtype)

print(new_array)

This resultantly creates an uninitialized array with the new, specified shape while preserving the data type of the original array:

[[4607182418800017408, 4607182418800017408],
 [4607182418800017408, 4607182418800017408],
 [4607182418800017408, 4607182418800017408]]

Conclusion

The numpy.empty_like() function is a powerful tool for initializing arrays expeditiously in Python’s NumPy library. Through the examples provided, we see its capability to create new arrays that have either the exact shape and data type as an existing array or, with a slight modification to our approach, arrays of a different shape but the same data type. Understanding and utilizing numpy.empty_like() can significantly streamline your data handling processes, especially when dealing with large datasets where initialization speed is critical. Remember, the function’s primary advantage is speed, achieved by foregoing the initialization of elements to any particular value. It is crucial to ensure that data in such arrays is subsequently overwritten with actual values to avoid unpredictable results stemming from the uninitialized state.