HOW TO RESHAPE ARRAY IN PYTHON NUMPY?

The method reshape() is used to reshape the python numpy array. Reshaping Python Numpy Array means changing the shape of an array by adding or removing dimensions or changing number of elements in each dimension.

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])

newarr = arr.reshape(4, 2)

print(newarr)

Output-

[[1 2]
 [3 4]
 [5 6]
 [7 8]]

Explanation-

arr.reshape(4, 2)- Convert the 1-D array- arr with 8 elements into a 2-D array.

The outermost dimension will have 4 arrays, each with 2 elements.

Note-

Requirement of elements in original array should meet the elements required in specified shape for conversion of original array.

for example- We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we cannot reshape it into a 3 elements 3 rows 2D array as that would require 3×3 = 9 elements. If the elements are short it will raise an error.

Unknown Dimension

We can specify one “unknown” dimension in reshape() method. We do not have to specify an exact number for one of the dimensions in the reshape method.

Pass -1 as the value, and NumPy will calculate this number for you.

import numpy as np

arr1 = np.array([1, 2, 3, 4, 5, 6, 7, 8])

newarr1 = arr1.reshape(2, 2, -1)

print(newarr1)

Output-

[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]

Flattening the arrays-

Converting a multidimensional array into a 1D array means flattening the array. We can use reshape(-1) to do this.

import numpy as np

arr1 = np.array([[1, 2, 3], [4, 5, 6]])

newarr1 = arr1.reshape(-1)

print(newarr1)

Output

[1 2 3 4 5 6]

Posted

in

Tags:

Comments

Leave a Reply