We have two similar kinds of ways to convert a ndarray to a 1D array of Flatten() and Ravel() Numpy function in Python programming language.
Example of Flatten() Numpy function
Here, we will create a Numpy array, and then by using flatten function we have changed the element in the flattened 1D NumPy array.
Python3
import numpy as np # Create a numpy array a = np.array([( 1 , 2 , 3 , 4 ),( 3 , 1 , 4 , 2 )]) # Let's print the array a print ( "Original array:\n " , a) # Convert nd array to 1D array c = a.flatten() # Flatten passes copy of # original array to 'c' print ( "\nFlatten array using flatten: " , c) |
Output:
Original array: [[1 2 3 4] [3 1 4 2]] Flatten array using flatten: [1 2 3 4 3 1 4 2]
The original 2D array is unchanged even if the value of the second member in the flattened 1D Numpy array was changed. This demonstrates that flatten() does return a copy of the Numpy input array.
Python3
c[ 2 ] = 33 print ( "Flatten array: " , c) # Let's print the array a print ( "\nOriginal array:\n " , a) |
Output:
Flatten array: [ 1 2 33 4 3 1 4 2] Original array: [[1 2 3 4] [3 1 4 2]]
Example of ravel() Numpy function
Here, we will create a Numpy array, and then by using the ravel() function we have changed the element in the flattened 1D NumPy array.
Python3
import numpy as np # Create a numpy array a = np.array([( 1 , 2 , 3 , 4 ),( 3 , 1 , 4 , 2 )]) # Let's print the array a print ( "Original array:\n " , a) ra = np.ravel(a) print ( "\nFlatten array using ravel: " , ra) |
Output:
`Original array: [[1 2 3 4] [3 1 4 2]] Flatten array using ravel: [1 2 3 4 3 1 4 2]
As we can see, The original 2D array is changed if the value of the second member in the flattened 1D Numpy array was changed. This demonstrates that ravel() returns a shallow copy of the Numpy input array.
Python3
ra[ 3 ] = 44 print ( "Flatten array: " , ra) # Let's print the array a print ( "\nOriginal array:\n " , a) |
Output:
Flatten array: [ 1 2 3 44 3 1 4 2] Original array: [[ 1 2 3 44] [ 3 1 4 2]]
Differences between Flatten() and Ravel()
ravel() |
flatten() |
---|---|
Return only reference/view of the original array | Return copy of the original array |
If you modify the array you would notice that the value of the original array also changes. | If you modify any value of this array value of the original array is not affected. |
Ravel is faster than flatten() as it does not occupy any memory. | Flatten() is comparatively slower than ravel() as it occupies memory. |
Ravel is a library-level function. | Flatten is a method of an ndarray object. Let us check out the difference in this code. |