.ravel()
The .ravel()
method returns a contiguous flattened array. It is used to convert a multi-dimensional array into a one-dimensional array. The returned array is a view of the original array whenever possible, meaning that it shares the same data buffer.
Syntax
ndarray.ravel(a, order='C')
Parameters:
a
: The input array to be flattened.order
: This parameter specifies the order in which the array elements are read. It can take the following values:'C'
: C-style row-major order (default).'F'
: Fortran-style column-major order.'A'
: ‘F’ if input is Fortran contiguous in memory, ‘C’ otherwise.'K'
: As close to the memory layout as possible.
Return value:
A flattened 1D array. Returns a view whenever possible, otherwise a copy.
Example 1
In this example, a 2D array is flattened into a 1D array using .ravel()
. The elements are listed in row-major order by default:
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])flattened_arr = np.ravel(arr)print(flattened_arr)
This produces the following output:
[1 2 3 4 5 6]
Example 2
In this example, a 3D array is flattened into a 1D array using .ravel()
. The elements are listed in row-major order by default:
import numpy as npthree_d_array = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])flattened_array = np.ravel(three_d_array)print(flattened_array)
This produces the following output:
[1 2 3 4 5 6 7 8]
Codebyte Example
Run the following codebyte example to understand the usage of the ravel()
method:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours