NumPy ndarray flatten in Python

In the tutorial, you will learn how to Convert a NumPy array to ndarray flatten in Python. The array means a collection of the same data items. The 2D array converts into a 1D array by using NumPy ndarray flatten in Python.

 Flatten in Python

The flatten() is a function that collapses the given array into a 1-dimension. The random memory changes to the next memory.

For suppose we consider the  2D array elements [1,2] and [3,4] at the positions [0][0] to [1][1] now by using the flatten functions these elements will changes 1D array [1,2,3,4] at positions [0] to [3] respectively.

Importing NumPy module:

importing the NumPy module as follows.

import numpy

Syntax of flatten:

The syntax of the flatten function as follows:
Syntax->numpy.ndarray.flatten(array name)

The 2D array will change to the corresponding 1D array structure.

Program on NumPy ndarray flatten:

import numpy
x=numpy.array([[11,2,30],[40,50,60]])
m=numpy.ndarray.flatten(x)
print(m)

Output:

[11  2 30 40 50 60]

Explanation:

  • Consider a 2D array stored in the x variable. The data as follows [[11 2 30 40 50 60]].
  • By using numpy.ndarray.flatten(x) method stored in m variable.
  • Now the data present in the “m” will be displayed as output.

Also read: How to flatten JSON objects in Python

Python List and Basic Python Set method

Leave a Reply

Your email address will not be published. Required fields are marked *