NumPy Tutorial NumPy Statistics NumPy References

NumPy - ndarray.flatten() function



The NumPy ndarray.flatten() function returns a copy of the array collapsed into one dimension. The syntax for using this function is given below:

Syntax

numpy.ndarray.flatten(order='C')

Parameters

order Optional. Specify order. It can take values from {'C', 'F', 'A', 'K'}. The default is 'C'.
  • 'C' - flatten in row-major (C-style) order.
  • 'F' - flatten in column-major (Fortran- style) order.
  • 'A' - flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise.
  • 'K' - flatten the array in the order the elements occur in memory.

Return Value

Returns a copy of the input array, flattened to one dimension.

Example: flatten() with C-like index ordering

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

import numpy as np
arr = np.array([[1,2,3],[4,5,6]])

#flatten the array
Narr = arr.flatten(order='C')

print("Original Array:")
print(arr)
print("\nFlattened Array:")
print(Narr)

The output of the above code will be:

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

Flattened Array:
[1 2 3 4 5 6]

Example: flatten() with F-like index ordering

To flatten 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]])

#flatten the array
Narr = arr.flatten(order='F')

print("Original Array:")
print(arr)
print("\nFlattened Array:")
print(Narr)

The output of the above code will be:

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

Flattened Array:
[1 4 2 5 3 6]

Example: flatten() 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)

#flatten using order='C'
print("\nFlattened Array (axis='C'):")
print(arr.flatten(order='C'))

#flatten using order='K'
print("\nFlattened Array (axis='K'):")
print(arr.flatten(order='K'))

The output of the above code will be:

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

 [[ 4  6]
  [ 5  7]]

 [[ 8 10]
  [ 9 11]]]

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

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

❮ NumPy - Array Manipulation