numpy.ndarray.flatten() in Python

In Python, for some cases, we need a one-dimensional array rather than a 2-D or multi-dimensional array. For this purpose, the numpy module provides a function called numpy.ndarray.flatten(), which returns a copy of the array in one dimensional rather than in 2-D or a multi-dimensional array.

Syntax

Parameters:

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:

y: ndarray

This function returns a copy of the source array, which gets flattened into one-dimensional.

Example 1:

Output:

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

In the above code

  • We have imported numpy with alias name np.
  • We have created a multi-dimensional array 'a' using array() function.
  • We have declared the variable 'b' and assigned the returned value of flatten() function.
  • Lastly, we tried to print the value of 'b'.

In the output, it shows a ndarray, which contains elements of the multi-dimensional array into 1-D.

Example 2:

Output:

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

In the above code

  • We have imported numpy with alias name np.
  • We have created a multi-dimensional array 'a' using array() function.
  • We have declared the variable 'b' and assigned the returned value of flatten() function.
  • We have used 'C' order in the function.
  • Lastly, we tried to print the value of 'b'.

In the output, it shows a ndarray, which contains elements of the multi-dimensional array into 1-D.

Example 3:

Output:

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

Example 4:

Output:

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

Example 5:

Output:

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





Latest Courses