Preferred way to preallocate NumPy arrays

In this tutorial, we will learn about the preferred way to preallocate NumPy arrays in Python. By Pranit Sharma Last updated : May 14, 2023

In NumPy, it is more efficient to preallocate a single array rather than call append/insert/concatenate.

When we resize an array by either append(), insert(), concatenate(), or resize(), there may be a need for copying the array to a larger block of memory and that is why preallocation is preferred over resizing.

What's the preferred way to preallocate NumPy arrays?

There are multiple ways for preallocating NumPy arrays based on your need. The following methods can be used to preallocate NumPy arrays:

  • numpy.zeros()
  • numpy.ones()
  • numpy.empty()
  • numpy.zeros_like()
  • numpy.ones_like(), and
  • numpy.empty_like()

And, the following methods can be used to create useful arrays:

  • numpy.linspace()
  • numpy.arange()

In the below-given example, we are using numpy.linspace() method. Let us understand with the help of an example.

Python program for preallocating NumPy arrays (preferred way)

# Import numpy
import numpy as np

# Creating an array
arr = np.linspace(10, 20, 16).reshape(4, 4)

# Display original array
print("Original array:\n", arr, "\n")

# make the last column all 1's
arr[:, -1] = 1

# Display result
print("Result:\n", arr, "\n")

Output

Original array:
 [[10.         10.66666667 11.33333333 12.        ]
 [12.66666667 13.33333333 14.         14.66666667]
 [15.33333333 16.         16.66666667 17.33333333]
 [18.         18.66666667 19.33333333 20.        ]] 

Result:
 [[10.         10.66666667 11.33333333  1.        ]
 [12.66666667 13.33333333 14.          1.        ]
 [15.33333333 16.         16.66666667  1.        ]
 [18.         18.66666667 19.33333333  1.        ]]

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.