Skip to main content

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]

Submitted by devanshi.srivastava on August 3, 2021

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

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.