NumPy Tutorial NumPy Statistics NumPy References

NumPy - ravel() function



The NumPy ravel() function returns a contiguous flattened array. The syntax for using this function is given below:

Syntax

numpy.ravel(a, order='C')

Parameters

a Required. Specify input array.
order Optional. Specify order. The elements of the array are read using this index order. It can take four possible values. The default is 'C'.
  • 'C' - read the index the elements in row-major, C-style order, with the last axis index changing fastest, back to the first axis index changing slowest.
  • 'F' - read the index the elements in column-major, Fortran-style order, with the first index changing fastest, and the last index changing slowest.
  • 'A' - read the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise.
  • 'K' - read the elements in the order they occur in memory, except for reversing the data when strides are negative.
Note: 'C' and 'F' options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing.

Return Value

Returns a contiguous flattened array with the same data type as input array and has shape equal to (a.size,).

Example: ravel() with C-like index ordering

By default ravel function uses row-major (C-style) order. Consider the example below.

import numpy as np
arr = np.array([[1,2,3],[4,5,6]])
print("Original Array:")
print(arr)

#ravel the array
Narr = np.ravel(arr, order='C')
print("\nRaveled Array:")
print(Narr)

The output of the above code will be:

Original Array:
[[1 2 3]
 [4 5 6]]

Raveled Array:
[1 2 3 4 5 6]

Example: ravel() with F-like index ordering

To ravel the array in column-major (Fortran- style) order, order='F' is used. Consider the example below.

import numpy as np
arr = np.array([[1,2,3],[4,5,6]])
print("Original Array:")
print(arr)

#ravel the array
Narr = np.ravel(arr, order='F')
print("\nRaveled Array:")
print(Narr)

The output of the above code will be:

Original Array:
[[1 2 3]
 [4 5 6]]

Raveled Array:
[1 4 2 5 3 6]

Example: ravel() with order='K'

When order='K', it will preserve orderings, but do not reverse axes. See the example below for more details.

import numpy as np
arr = np.arange(12).reshape(3,2,2).swapaxes(1,2);
print("Original Array:")
print(arr)

#ravel using order='C'
print("\nRaveled Array (axis='C'):")
print(np.ravel(arr, order='C'))

#ravel using order='K'
print("\nRaveled Array (axis='K'):")
print(np.ravel(arr, order='K'))

The output of the above code will be:

Original Array:
[[[ 0  2]
  [ 1  3]]

 [[ 4  6]
  [ 5  7]]

 [[ 8 10]
  [ 9 11]]]

Raveled Array (axis='C'):
[ 0  2  1  3  4  6  5  7  8 10  9 11]

Raveled Array (axis='K'):
[ 0  1  2  3  4  5  6  7  8  9 10 11]

❮ NumPy - Array Manipulation