numpy.ravel() in Python
The numpy.ravel() returns a contiguous flattened array(1-D array), containing the elements of the input.
Syntax
numpy.ravel(a, order='C')
Parameter
The numpy.ravel() method consists of two parameters, which are as follows:
a: This parameter represents an Input array. The elements in ‘a’ are read in the order specified by order, and packed as a 1-D array.
order : This parameter can be either C_contiguous or F_contiguous where C order operates row-rise on the array and F order operates column-wise operations.
Return
This function returns an array of the same subtype as parameter ‘a’, with shape (a.size,).
Example 1
# Python Program illustrating
# numpy.ravel() method
import numpy as np
import numpy as np
arr = np.arange(8).reshape(2,4)
print ('The original array:')
print (arr,"\n")
print ('After applying ravel function:')
print (arr.ravel())
#Maintaining F order
print ('ravel function in F-style ordering:')
print (arr.ravel(order = 'F'))
#K-order preserving the ordering
print("\nnumpy.ravel() function in K-style ordering: ", arr.ravel(order= 'K'))
Output
The original array:
[[0 1 2 3]
[4 5 6 7]]
After applying ravel function:
[0 1 2 3 4 5 6 7]
ravel function in F-style ordering:
[0 4 1 5 2 6 3 7]
numpy.ravel() function in K-style ordering: [0 1 2 3 4 5 6 7]
Example 2
# Python Program illustrating
# numpy.ravel() method
import numpy as np
arr = np.arange(15).reshape(3, 5)
print("Array: \n", arr)
# calling the numpy.ravel() function
print("\nravel() value: ", arr.ravel())
# ravel() is equivalent to reshape(-1, order=order).
print("\nnumpy.ravel() == numpy.reshape(-1)")
print("Reshaping array : ", arr.reshape(-1))
Output
Array:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
ravel() value: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
numpy.ravel() == numpy.reshape(-1)
Reshaping array : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]