numpy.ndarray.flatten() – The NumPy ndarray flatten Python Function

NumPy ndarray flatten: Introduction

The numpy.ndarray.flatten() function returns a one-dimensional copy of the array.

Syntax:

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

Parameters:

  • order : [{‘C’, ‘F’, ‘A’, ‘K’}, optional] ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten an in the order the elements occur in memory. The default is ‘C’.

Return: [ndarray] A copy of the input array, flattened to one dimension.

NumPy ndarray flatten: Code Examples

Example 01:

# welcome to softhunt.net
# Python program explaining
# numpy.ndarray.flatten() function

# importing numpy as np
import numpy as np


arr = np.array([[2, 3], [4, 5]])

softhunt = arr.flatten()

print( softhunt )

Output:

[2 3 4 5]

Example 02:

# welcome to softhunt.net
# Python program explaining
# numpy.ndarray.flatten() function

# importing numpy as np
import numpy as np

arr = np.array([[8, 7], [6, 5]])

softhunt = arr.flatten('F')

print( softhunt )

Output:

[8 6 7 5]

FAQs

Differences between Flatten() and Ravel() Numpy Functions

They have similar kinds of ways to convert a ndarray to a 1D array: Flatten() and Ravel(). But here is the difference.

a.Ravel():

  1. Return only reference/view of the original array
  2. If you modify the array you would notice that the value of the original array also changes.
  3. Ravel is faster than flatten() as it does not occupy any memory.
  4. Ravel is a library-level function.

a.flatten():

  1. Return copy of original array
  2. If you modify any value of this array value of an original array is not affected.
  3. Flatten() is comparatively slower than ravel() as it occupies memory.
  4. Flatten is a method of a ndarray object.

How do you convert Ndarray to a 1D array?

Use numpy.array.flatten() to convert a 2D NumPy array into a 1D array

  1. print(array_2d)
  2. array_1d = array_2d. flatten() flatten array_2d
  3. print(array_1d)

Convert 2D Numpy array to 1D Numpy array using numpy.ravel()

  1. arr = np. array([[0, 1, 2], [3, 4, 5],
  2. [6, 7, 8]])flat_array = np. ravel(arr)
  3. print(‘Flattened 1D Numpy array:’)
  4. print(flat_array)

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn. And make sure you check out our NumPy tutorials.

Suggested Articles:

  1. numpy.ravel() – The NumPy ravel Python Function
  2. numpy.ndarray.flat – The NumPy ndarray flat Python Function

Leave a Comment