Numpy : Difference between flatten and raveal
Yeshwanth Nagaraj
Democratizing Math and Core AI // Levelling playfield for the future
In NumPy, both the flatten() and ravel() functions are used to convert multidimensional arrays into one-dimensional arrays. However, there are a few differences between these two functions:
Here's an example to illustrate these differences:
领英推荐
import numpy as np
# Creating a 2D array
arr = np.array([[1, 2, 3],
? ? ? ? ? ? ? ? [4, 5, 6]])
# Using flatten()
flattened = arr.flatten()
flattened[0] = 10? # Modifying the flattened array
# Using ravel()
raveled = arr.ravel()
raveled[0] = 20? # Modifying the raveled array
print(arr)
print(flattened)
print(raveled)
Output :
[[1 2 3]
?[4 5 6]]
[10? 2? 3? 4? 5? 6]
[20? 2? 3? 4? 5? 6]
In the example, modifying the flattened array does not change the original arr. However, modifying the raveled array also modifies the original arr because it is a view sharing the same data.
Overall, the main differences between flatten() and ravel() in NumPy are related to return types (copy vs. view), memory contiguity, performance, and their impact on modifying the original array.