We have two similar kind of ways to convert a ndarray to 1D array : Flatten() and Ravel()
import numpy as np a = np.array( [ (1,7,3,4),(3,2,4,1) ] ) #OUTPUT: print( a.flatten() ) # [ 1,7,3,4,3,2,4,1 ] print ( a.ravel() ) # [ 1,7,3,4,3,2,4,1 ]
The question arises here, why are there two numpy functions to do the same task ?
Differences between Flatten() and Ravel()
(i) Return only reference/view of original array
(ii) If you modify the array you would notice that the value of original array also changes.
(iii) Ravel is faster than flatten() as it does not occupy any memory.
(iv) Ravel is a library-level function.
(i) Return copy of original array
(ii) If you modify any value of this array value of original array is not affected.
(iii) Flatten() is comparatively slower than ravel() as it occupies memory.
(iv) Flatten is a method of an ndarray object.
Let us check out the difference by this code
OUTPUT: Original array: [[1 2 3 4] [3 1 4 2]] Dimension of array-> 2 Output for RAVEL [1 2 3 4 3 1 4 2] [1000 2 3 4 3 1 4 2] [[1000 2 3 4] [ 3 1 4 2]] Dimension of array-> 1 Output for FLATTEN [1000 2 3 4 3 1 4 2] [0 2 3 4 3 1 4 2] [[1000 2 3 4] [ 3 1 4 2]] Dimension of array-> 1
This article is contributed by SHAURYA UPPAL.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- numpy.ravel() in Python
- Python | Numpy matrix.ravel()
- Numpy recarray.ravel() function | Python
- Numpy MaskedArray.ravel() function | Python
- Python | Numpy matrix.flatten()
- Numpy ndarray.flatten() function | Python
- Numpy MaskedArray.flatten() function | Python
- Numpy recarray.flatten() function | Python
- Python | Flatten a 2d numpy array into 1d array
- Python | Pandas TimedeltaIndex.ravel
- Python | Pandas Series.ravel()
- Python | Flatten given list of dictionaries
- Python - Flatten Nested Keys
- Python - Flatten Nested Tuples
- Python - Distinct Flatten dictionaries
- Python | Ways to flatten a 2D list
- Python - Flatten Dictionary with List
- Python | Flatten Tuples List to String
- Python | Flatten and Reverse Sort Matrix
- Python - Flatten List to individual elements