Reshaping the NumPy array objects

Reshaping of array means changing the shape of an array, Reshaping an array means that we can add or remove dimensions or change number of elements in each dimension. It also gives Information about the shape and  dimension of an array. It gives new shape to an array without changing its data.

Syntax:

array_name.reshape(shape)

It is used to return a numpy array containing the same data with a new shape.

Example:

1-D to 2-D:

import numpy as np
a=np.array(['a','b','c','d','e','f','g','h','i','j','k','l'])
new_array = a.reshape(2,6)
print(new_array)

Output:

[['a' 'b' 'c' 'd' 'e' 'f']
 ['g' 'h' 'i' 'j' 'k' 'l']]

1-D to 3-D:

import numpy as np
a=np.array(['a','b','c','d','e','f','g','h','i','j','k','l'])
new_array=a.reshape(2,2,3)
print(new_array)

Output:

[[['a' 'b' 'c']
  ['d' 'e' 'f']]

 [['g' 'h' 'i']
  ['j' 'k' 'l']]]

N-D to 1-D:

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

Output: [1 2 3 4 5 6]

Tue, 08/03/2021 - 20:26

Authored by

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.