Javatpoint Logo
Javatpoint Logo

numpy.ravel() in Python

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.

Syntax:

Parameters:

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'.

Returns:

This function returns a contiguous flatten array with the same data type as an input array and has shape equal to (x.size).

Example 1:

Output:

array([ 1,  3,  5, 11, 35, 56])

In the above code

  • We have imported numpy with alias name np.
  • We have created an array 'x' using np.array() function.
  • We have declared variable y and assigned the returned value of np.ravel() function.
  • We have passed the array 'x' in the function.
  • Lastly, we tried to print the value of y.

In the output, the values of the array are shown in a contiguous flattened array.

Example 2:

Output:

array([ 1, 11,  3, 35,  5, 56])
array([ 1,  3,  5, 11, 35, 56])
array([ 1,  3,  5, 11, 35, 56])
array([ 1,  3,  5, 11, 35, 56])

Example 3:

Output:

array([[[ 0,  2],
        	[ 1,  3]],

       	[[ 4,  6],
        	[ 5,  7]],

       	[[ 8, 10],
        	[ 9, 11]]])
array([ 0,  2,  1,  3,  4,  6,  5,  7,  8, 10,  9, 11])
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
array([ 0,  2,  1,  3,  4,  6,  5,  7,  8, 10,  9, 11])

In the above code

  • We have imported numpy with alias name np.
  • We have created an array 'x' using np.arange() function.
  • We have changed its shape and swapped the axis using the reshape() and np.swapaxes() function.
  • We have declared the variables y, z, and q and assigned the returned value of np.ravel() function.
  • We have passed the array 'x' and order C, K, and A in the function.
  • Lastly, we tried to print the value of y.

In the output, the values of the array are shown in a contiguous flattened array.


Next TopicNumpy.save()




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA