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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Python | Numpy matrix.ravel()
- Numpy recarray.ravel() function | Python
- Numpy MaskedArray.ravel() function | Python
- numpy.ravel() in Python
- Python | Pandas TimedeltaIndex.ravel
- Python | Pandas Series.ravel()
- Python | Flatten a 2d numpy array into 1d array
- Python | Numpy matrix.flatten()
- Numpy recarray.flatten() function | Python
- Numpy MaskedArray.flatten() function | Python
- Numpy ndarray.flatten() function | Python
- Flatten a Matrix in Python using NumPy
- Flatten A list of NumPy arrays
- Difference between regular functions and arrow functions
- Python | Flatten and Reverse Sort Matrix
- Python - Flatten and remove keys from Dictionary
- Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
- Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)
- Mathematical Functions in Python | Set 4 (Special Functions and Constants)
- Python | Ways to flatten a 2D list