Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

numpy
communitycreator

How to reshape an array in Numpy

Onyejiaku Theophilus Chidalu

Overview

The shape of an array is simply the number of elements present in the array in any dimension. Reshaping an array means changing the number of elements in each given dimension. An array could by one dimensional 1D, two dimensional 2D, three dimensional 3D, and so on. Changing an array, let’s say, from 1D to 2D is referred to as reshaping the array.

When reshaping an array, the new shape should be equal in length to the original shape. In other words, the elements required for reshaping must be equal in both shapes.

How to reshape an array

The array.reshape() function reshapes an array in NumPy. This function gives a new shape to an array without changing its data.

Syntax

array.reshape(shape)

Parameter value

The array.reshape() method takes a tuple as its parameter value. The tuple represents the new shape to be created.

Return value

The array.reshape() returns numpy.ndarray.

Reshaping from 1D to 2D

We create a 1D array with eight elements in the code below. We then reshape it to another equal shape but of a 2D array with four arrays and two elements in each dimension.

Code

import numpy as np

# creating an array
myarray = np.array([1, 2, 3, 4, 5, 6, 7, 8])

# reshaping the 
newarray = myarray.reshape(4, 2)

print(newarray)
Reshaping from 1D to 2D

Code explanation

  • Line 1: We import the numpy module
  • Line 4: we create a 1D array, myarray, with eight elements
  • Line 7: We use the array.reshape() function to reshape the existing array. We reshape it to an array with four arrays, each having two elements on them ( i.e., (4, 2)). The output is assigned to a new array variable, newarray.
  • Line 9: We print the reshaped newarray.

Reshaping from 1D to 3D

In the example below, we reshape a 1D array with 12 elements into a 3D array with three arrays that contain two arrays with two elements each.

Code

import numpy as np

# creating a 1D array
myarray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# reshaping the 1D array to a 3D array with has 3 arrays containing 2 arrays with 2 elements each
newarray = myarray.reshape(3, 2, 2)

print(newarray)
Reshaping from 1D to 3D

Code explanation

  • Line 1: We import the numpy module.
  • Line 4: We create a 1D array myarray with 12 elements.
  • Line 7: We use the array.reshape() function to reshape the existing array. We change it to an array with three arrays containing two arrays with two elements each (i.e., (3, 2, 2)). The output is assigned to a new array variable, newarray.
  • Line 9: We print the reshaped array newarray.

RELATED TAGS

numpy
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring