Facebook Page Twitter Page LinkedIn Page
× NumPy Tutorial NumPy Resources


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 four possible values. 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 ndarray, 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]])
print("Original Array:")
print(arr)

#flatten the array
f_arr = arr.flatten(order='C')
print("\nFlattened Array:")
print(f_arr)

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]])
print("Original Array:")
print(arr)

#flatten the array
f_arr = arr.flatten(order='F')
print("\nFlattened Array:")
print(f_arr)

The output of the above code will be:

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

Flattened Array:
[1 4 2 5 3 6]

❮ NumPy - Functions

5