Create a contiguous flattened NumPy array
Let us see how to create a contiguous array in NumPy.The contiguous flattened array is a two-dimensional and multi-dimensional array that is stored as a one-dimensional array. We will be using the ravel() method to perform this task.
Syntax : numpy.ravel(array, order = ‘C’)
Parameters :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. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
- array : Input array.
- order : C-contiguous, F-contiguous, A-contiguous; optional
Returns : Flattened array having same type as the Input array and and order as per choice.
Example 1 : Flattening a 2D array.
Python3
# Importing librariesimport numpy as np # Creating 2D arrayarr = np.array([[5, 6, 7], [8, 9, 10]])print("Original array:\n", arr) # Flattening the arrayflattened_array = np.ravel(arr)print("New flattened array:\n", flattened_array) |
Output :
Original array: [[ 5 6 7] [ 8 9 10]] New flattened array: [ 5 6 7 8 9 10]
Example 2 : Flattening a 3D array.
Python3
# Importing librariesimport numpy as np # Creating 3D arrayarr = np.array([[[3, 4], [5, 6]], [[7, 8], [9, 0]]])print("Original array:\n", arr) # Flattening the arrayflattened_array = np.ravel(arr)print("New flattened array:\n", flattened_array) |
Output :
Original array: [[[3 4] [5 6]] [[7 8] [9 0]]] New flattened array: [3 4 5 6 7 8 9 0]


