How to Use the Python numpy.ravel() Function

09/09/2021

Contents

In this article, you will learn how to use the Python numpy.ravel() function.

Python numpy.ravel() Function

The numpy.ravel() function is used to flatten a multi-dimensional array into a one-dimensional array in NumPy, a popular numerical computing library for Python.

Here’s how you can use the numpy.ravel() function:

import numpy as np

# Create a multi-dimensional array
array = np.array([[1, 2, 3], [4, 5, 6]])

# Flatten the array using numpy.ravel()
flattened_array = np.ravel(array)

print(flattened_array)
# Output: [1 2 3 4 5 6]

The numpy.ravel() function returns a flattened view of the input array whenever possible, so modifying the flattened array will modify the original array. If you need a copy of the flattened array, you can use the numpy.flatten() function instead.

Here’s an example to demonstrate the difference between numpy.ravel() and numpy.flatten():

import numpy as np

# Create a multi-dimensional array
array = np.array([[1, 2, 3], [4, 5, 6]])

# Flatten the array using numpy.ravel()
flattened_array = np.ravel(array)

# Modify the flattened array
flattened_array[0] = 10

print(array)
# Output: [[10, 2, 3], [4, 5, 6]]

# Flatten the array using numpy.flatten()
flattened_array = np.flatten(array)

# Modify the flattened array
flattened_array[0] = 1

print(array)
# Output: [[10, 2, 3], [4, 5, 6]]

As you can see from the output, modifying the flattened array obtained from numpy.ravel() also modifies the original array, whereas modifying the flattened array obtained from numpy.flatten() does not modify the original array.

Here’s more information on the numpy.ravel() function in NumPy:

  • The numpy.ravel() function is faster than the numpy.flatten() function because it returns a flattened view of the input array whenever possible, which means it avoids copying the data. However, this means that modifying the flattened array will modify the original array, so you need to be careful when using numpy.ravel().
  • The numpy.ravel() function is also more memory-efficient than numpy.flatten() because it does not create a copy of the data.