The numpy.ravel() function is used to flatten a NumPy array into a one-dimensional array. It returns the elements in the specified order and creates a copy only when required.
Example: Flatten a NumPy Array
import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(arr.ravel())
Output
[1 2 3 4]
Explanation:
- np.arange(6) creates an array containing values from 0 to 5.
- reshape(2, 3) arranges these values into 2 rows and 3 columns.
- np.ravel(arr) converts the 2D array into a 1D array.
- The result contains all elements in row-wise order.
Syntax
numpy.ravel(a, order='C')
Parameters:
- a - Specifies the input array.
- order - Specifies the order in which elements are read. It can be 'C', 'F', 'A', or 'K'.
Return Value: Returns a flattened one-dimensional array with the same data type as the input array.
Examples
Example 1: Flatten a 2D Array
The uses ravel() to flatten a two-dimensional NumPy array.
import numpy as np
arr = np.arange(6).reshape(2, 3)
result = np.ravel(arr)
print(result)
Output
[0 1 2 3 4 5]
Explanation:
- np.arange(6) creates values from 0 to 5.
- reshape(2, 3) arranges the values into 2 rows and 3 columns.
- np.ravel(arr) converts the 2D array into a 1D array.
- The elements are returned in row-wise order by default.
Example 2: Using C and F Order
The shows how the order parameter affects the arrangement of elements.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("C order:", arr.ravel(order='C'))
print("F order:", arr.ravel(order='F'))
Output
('C order:', array([1, 2, 3, 4, 5, 6]))
('F order:', array([1, 4, 2, 5, 3, 6]))
Explanation:
- order='C' reads the elements row-wise.
- order='F' reads the elements column-wise.
- C order returns [1, 2, 3, 4, 5, 6].
- F order returns [1, 4, 2, 5, 3, 6].
Example 3: Using A Order
The uses 'A' order to determine the element order based on the array's memory layout.
import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(arr.ravel(order='A'))
Output
[1 2 3 4]
Explanation:
- order='A' checks the memory layout of the array.
- It uses Fortran-style ordering if the array is Fortran-contiguous.
- Otherwise, it uses C-style ordering.
- The given array uses C-style ordering, so the result is [1, 2, 3, 4].
Example 4: Using K Order
The uses 'K' order to preserve the elements according to their memory layout.
import numpy as np
arr = np.arange(12).reshape(2, 3, 2).swapaxes(1, 2)
print(arr)
print(arr.ravel(order='K'))
Output
[[[ 0 2 4] [ 1 3 5]] [[ 6 8 10] [ 7 9 11]]] [ 0 1 2 3 4 5 6 7 8 9 10 11]
Explanation:
- np.arange(12) creates values from 0 to 11.
- reshape(2, 3, 2) creates a three-dimensional array.
- swapaxes(1, 2) changes the positions of the second and third axes.
- ravel(order='K') reads the elements according to their memory layout.
- The result is a one-dimensional array containing all elements.
Note : These codes won’t run on online IDE's. Please run them on your systems to explore the working.