What is the numpy.ravel() function from NumPy in Python?
Overview
Python’s ravel() function is used to return a contiguous array. This function returns a 1D array that contains the input elements.
Syntax
The syntax for this function is as follows:
numpy.ravel(a, order='C')
Parameter value
The ravel() function takes the following parameter values:
a: This represents the input array.order: This represents the type of order for the memory layout. This parameter value is optional. It can take a"C","F","A", or"K'order.
Return value
The ravel() function returns an array of the same subtype and shape as that of the input array a that is passed to it.
Code example
import numpy as np# creating an arraymyarray1 = np.array([[1, 2, 3], [4, 5, 6]])# calling the ravel() functionmyarray2 = np.ravel(myarray1, order = "K")print(myarray2)# checking the size of the imput and output arraysprint(myarray1.size)print(myarray2.size)
Code explanation
- Line 1: We import the
numpymodule. - Line 3: We create a
2Darray calledmyarray1, using thearray()function. - Line 6: We implement the ravel() function on the variable
myarray1, using an order styleK. We assign the result to another variable calledmyarray2. - Line 8: We print the array
myarray2. - Lines 11–12: To confirm if both the input and output array are of the same size, we obtain and print their sizes with the
array.size()function.