numpy.ravel() in Python

numpy.ravel() is a function present in numpy module which allows us to change a 2 dimensional or multi dimensional array into a contiguous flattened array i.e 1 dimensional array with all input elements and of same type as it. A copy is made only when needed. If input array is masked then returned array is also masked.

Syntax:

numpy.ravel(x, order=’C’)

Parameters:

x : array_like

This reads the input array and all the elements are read in the order specified by the order parameter.

order:{‘C’,’F’,’A’,’K’} (optional)

This order parameter is optional.

  • Order parameter ‘C’ means array flattens in row major order. The last axis change is fastest and the first axis change is slowest.
  • Order parameter ‘F’  (Fortran contiguous memory order) means array flattens in the column major order. Here the first axis change is fastest and last axis change is slowest.
  • Order parameter ‘A’ means read / write elements in Fortran like index order only if array is fortran contiguous memory order otherwise C like order.
  • Order parameter ‘K’ means read / write elements in order present as it is in the system.

Returns:

This function returns a contiguous flattened array with same data type as input array and has equal size (x.size)

Example1:

import numpy as np 

x = np.array([[4, 7, 8, 9], [16, 24, 86,45]]) 

y=np.ravel(x) 

y

Example2:

import numpy as np

x = np.array([[23, 76, 11, 42], [74, 91, 8, 34]])

y = np.ravel(x)

print('Flattened array: \n', y)

y[1] = 121

print('Original array: \n', x)

The above example shows that any changes in flattened array will reflect in original array as you can see that value y[1] = 121 is changed in original array as well.

Example3:

import numpy as np

a = np.arange(12).reshape(3,4)

print('The original array is:\n',a)

print('\n') 

print('After applying ravel function:',a.ravel())

print('\n' )

print('Applying ravel function in F-style ordering:',a.ravel(order = 'F'))

print('Applying ravel function in C-style ordering:',a.ravel(order = 'C'))

print('Applying ravel function in K-style ordering:',a.ravel(order = 'K'))

print('Applying ravel function in A-style ordering:',a.ravel(order = 'A'))

With the above examples we have seen about the ravel function and its ordering styles in detail. Now if you want to know more about numpy click here!