The numpy module of Python provides a function called numpy.ravel, which is used to change a 2-dimensional array or a multi-dimensional array into a contiguous flattened array. The returned array has the same data type as the source array or input array. If the input array is a masked array, the returned array will also be a masked array.
numpy.ravel(x, order='C')
x: array_like
This parameter defines the input array, which we want to change in a contiguous flattened array. The array elements are read in the order specified by the order parameter and packed as a 1-D array.
order: {'C','F', 'A', 'K'}(optional)
If we set the order parameter to 'C', it means that the array gets flattened in row-major order. If 'F' is set, the array gets flattened in column-major order. The array is flattened in column-major order only when 'A' is Fortran contiguous in memory, and when we set the order parameter to 'A'. The last order is 'K', which flatten the array in same order in which the elements occurred in the memory. By default, this parameter is set to 'C'.
This function returns a contiguous flatten array with the same data type as an input array and has shape equal to (x.size).
import numpy as np x = np.array([[1, 3, 5], [11, 35, 56]]) y=np.ravel(x) y
Output:
In the above code
In the output, the values of the array are shown in a contiguous flattened array.
import numpy as np x = np.array([[1, 3, 5], [11, 35, 56]]) y = np.ravel(x, order='F') z = np.ravel(x, order='C') p = np.ravel(x, order='A') q = np.ravel(x, order='K') y z p q
Output:
import numpy as np x = np.arange(12).reshape(3,2,2).swapaxes(1,2) x y=np.ravel(a, order='C') y z=np.ravel(a, order='K') z q=np.ravel(a, order='A') q
Output:
In the above code
In the output, the values of the array are shown in a contiguous flattened array.