NumPy flatten() - Convert the 2D or 3D array to 1D array | Python

NumPy flatten() converts the multi-dimensional array to the "flattened" 1D array.

import numpy

a1 = numpy.array([1, 2])
a2 = numpy.array([[1, 2], [3, 4]])
a3 = numpy.array([[1, 2], [3, 4], [5, 6]])

f1 = a1.flatten()
f2 = a2.flatten()
f3 = a3.flatten()

print(f1)  # [1 2]
print(f2)  # [1 2 3 4]
print(f3)  # [1 2 3 4 5 6]

ndarray.flatten() and reshape()

The reshape() converts the 1D array to 2D array.

import numpy

a = numpy.array([1, 2, 3, 4, 5, 6])
b = a.reshape(2, 3)

print(b)
# [[1 2 3]
#  [4 5 6]]

c = numpy.ndarray.flatten(b)
print(c)
# [1 2 3 4 5 6]

Comments

Powered by Markdown

More