Have you ever thought, why there are two functions for transforming multi-dimensional array to one-dimensional array? Which one is best for me? flatten() or ravel(). This tutorial will answer you by comparing them one by one.
Numpy ravel() | Numpy flatten() |
---|---|
ravel() function simply returns a flattened view of Numpy array. |
flatten() function returns a flattened copy of Numpy array. |
If you try to modify the flattened view then you end up with that same change in the original array. | Changes made to flattened array is not reflected back to the original array. |
ravel() does not occupy memory so we can say that it is faster than flatten() |
flatten() occupies memory so it is considered slower than ravel() function. |
Let's understand the second difference with the help of an example-
#Python program to clarify the difference between ravel() and flatten() import numpy as np print('Checking ravel()') x = np.array([[40, 32, 67], [61, 79, 15]]) print('Original array:\n', x) y = x.ravel() print() y[1] = 1000 print('Original array after making changes in flattened array:\n', x) print('\nChecking flatten()') a = np.array([[40, 32, 67], [61, 79, 15]]) print('Original array:\n', a) b = a.flatten() print() b[1] = 1000 print('Original array after making changes in flattened array:\n', a)
Output of the above program
Checking ravel() Original array: [[40 32 67] [61 79 15]] Original array after making changes in flattened array: [[ 40 1000 67] [ 61 79 15]] Checking flatten() Original array: [[40 32 67] [61 79 15]] Original array after making changes in flattened array: [[40 32 67] [61 79 15]]