Understanding NumPy’s ravel()
The ravel()
function takes a NumPy array (of any dimension) as input and returns a flattened 1D array containing all the elements of the original array. Crucially, it returns a view of the original array, not a copy. This means changes made to the flattened array will be reflected in the original array, and vice-versa, leading to memory efficiency.
Example 1: Basic Flattening
Let’s start with a simple 2D array:
import numpy as np
= np.array([[1, 2, 3], [4, 5, 6]])
arr_2d = arr_2d.ravel()
flattened_arr
print("Original Array:\n", arr_2d)
print("\nFlattened Array:", flattened_arr)
This will output:
Original Array:
[[1 2 3]
[4 5 6]]
Flattened Array: [1 2 3 4 5 6]
Example 2: Higher-Dimensional Arrays
ravel()
works seamlessly with arrays of any dimension:
= np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
arr_3d = arr_3d.ravel()
flattened_arr
print("Original 3D Array:\n", arr_3d)
print("\nFlattened Array:", flattened_arr)
This will produce a single 1D array containing all elements from the 3D array.
Example 3: Modifying a View
Remember, ravel()
returns a view. Changes to the flattened array affect the original:
= np.array([[1, 2, 3], [4, 5, 6]])
arr_2d = arr_2d.ravel()
flattened_arr 0] = 100
flattened_arr[
print("Modified Flattened Array:", flattened_arr)
print("\nOriginal Array (Modified):\n", arr_2d)
Observe how altering the flattened array changes the original 2D array.
Example 4: flatten()
– The Copy Alternative
While ravel()
returns a view, the flatten()
method returns a copy of the flattened array. Modifications to the flattened array won’t affect the original array:
= np.array([[1, 2, 3], [4, 5, 6]])
arr_2d = arr_2d.flatten()
flattened_copy 0] = 100
flattened_copy[
print("Modified Flattened Copy:", flattened_copy)
print("\nOriginal Array (Unchanged):\n", arr_2d)
When to Use ravel()
ravel()
proves exceptionally useful in scenarios requiring efficient array flattening, especially when memory conservation is a priority. Its ‘view’ characteristic is advantageous when manipulating large datasets, preventing unnecessary memory duplication. Use flatten()
when you need an independent copy of the flattened data.
Beyond the Basics: Order Considerations
By default, ravel()
flattens the array in C-style order (row-major). For Fortran-style order (column-major), you can specify the order
parameter:
= np.array([[1, 2, 3], [4, 5, 6]])
arr_2d = arr_2d.ravel(order='F')
flattened_fortran print(flattened_fortran) # Output: [1 4 2 5 3 6]