The ravel() method flattens a NumPy array without changing its data.
ravel() Syntax
The syntax of ravel() is:
numpy.ravel(array, order)
ravel() Arguments
The ravel() method takes two arguments:
array- an original array that is to be flattenedorder(optional) - specifies the order in which the array elements are flattened
ravel() Return Value
The ravel() method returns the flattened array.
Example 1: Flatten a Multidimensional Array
Output
[0 1 2 3 4 5 6 7]
Using Optional Order Argument in ravel()
The order argument specifies the order in which the array elements are flattened.
The order can be:
'C'- flattens the elements row-wise (in C-style order)'F'- flattens the elements column-wise (in Fortran-style order)'A'- tries to preserve the original array's order, otherwise defaults to C-order.'K'- flattens the elements in the order they occur in memory, and uses C-order by default.
Output
C: [0 1 2 3 4 5 6 7] F: [0 4 2 6 1 5 3 7] A: [0 1 2 3 4 5 6 7] K: [0 4 2 6 1 5 3 7]
Difference Between Flatten and Ravel
The key differences between flatten() and ravel() are
flatten()is anndarrayobject method whereasravel()is a library-level function. For example,
Output
[1 2 3 4] [1 2 3 4]
ravel()works with a list of arrays, butflatten()doesn't.
Output
[1 2 3 4] Traceback (most recent call last): File "<string>", line 13, in <module> ERROR! AttributeError: 'list' object has no attribute 'flatten'
flatten()always returns a copy of the original array whereasravel()makes a copy only when necessary.
To learn more, visit NumPy flatten().