Flattening the Numpy arrays

Flattening an array means converting an array to a 1D array. We can use reshape(-1) to do this.

Example 1

Convert a 3D array into a 1D array

Python3




import numpy as np
  
a = np.array([['G', 'F', 'G'],
              ['G', 'F', 'G'], 
              ['G', 'F', 'G']])
na = a.reshape(-1)
print(na)


Output:

[‘G’ ‘F’ ‘G’ ‘G’ ‘F’ ‘G’ ‘G’ ‘F’ ‘G’]

Example 2

Convert the 2D array into a 1D array:

Python3




import numpy as np
  
arr = np.array([[1, 2, 3], [4, 5, 6]])
newarr = arr.reshape(-1)
print(newarr)


Output:

[1 2 3 4 5 6]


What does -1 mean in numpy reshape?

While working with arrays many times we come across situations where we need to change the shape of that array but it is a very time-consuming process because first, we copy the data and then arrange it into the desired shape, but in Python, we have a function called reshape() for this purpose.

Similar Reads

What is numpy.reshape() in Python

The numpy.reshape() function shapes an array without changing the data of the array....

Finding Unknown Dimensions in Numpy

...

Flattening the Numpy arrays

When we are unaware of any dimension of the array then we are allowed to have only one “unknown” dimension. This represents that we do not have to specify any number for one of that dimensions in the reshape method. We pass -1 as the value for the unknown dimension, and NumPy will calculate this unknown....