Array Shape & Reshape In NUMPY

In this post, we’ll dive into the details of NumPy array shape and reshape, covering the basics of reshaping Numpy arrays and the use of reshape() function to change the shape of an array.

NumPy Array Shape

The shape of an array refers to the number of elements along each dimension of the array.

Numpy arrays can have one or more dimensions, and the shape of an array is represented as a tuple of integers, where each integer represents the size of an array along a particular dimension.

Understanding the shape of an array is crucial for efficiently manipulating and processing data in Numpy, as well as for selecting and slicing elements from arrays.

In this section of article, we’ll explore the concept of array shape and how to access and modify Numpy array shape.



Get NumPY Array Shape

In Numpy Array shape, Numpy arrays have an attribute known as shape that provides a tuple with the number of items for each index.

The shape of a 2-D array can be displayed as follows:

NumPy Array Shape Example: 1 

import numpy as npy mrx_arr = npy.array([[0, 2, 4, 6, 8, 10], [1, 3, 5, 7, 9, 11]]) print(mrx_arr.shape)

According to the example above, we return (2, 6), which indicates that the array has two dimensions, and every dimension has six items.

A 3-D array shape can be represented as follows:

NumPy Array Shape Example: 2 

import numpy as npy mrx_arr = npy.array([[["New York City", "Los Angeles", "Chicago"], ["Houston", "Phoenix ", "Philadelphia"]], [["San Antonio", "San Antonio", "Dallas "], ["San Jose", "Austin, TX", "Jacksonville, FLA"]]]) print(mrx_arr.shape)

In the example above, it indicates that the array has three dimensions, and each dimension has three items.

With ndmin, generate a 9-dimensional array with elements 2, 3, 5, 7, 11, 13, 17, 19, and make sure that the final dimension has value 8:

NumPy Array Shape Example: 3 

import numpy as npy prime_arr = npy.array([2, 3, 5, 7, 11, 13, 17, 19], ndmin=9) print(prime_arr) print('Array Shape:', prime_arr.shape)

Utilizing ndmin, build a 6-dimensional array with components B, C, D, F, G, H, and ensure that the last dimension is 6:

NumPy Array Shape Example: 4 

import numpy as npy consonants_arr = npy.array(['B', 'C', 'D', 'F', 'G', 'H'], ndmin=6) print(consonants_arr) print('Array Shape:', consonants_arr.shape)

How does the shape tuple work?

The shape tuple in Numpy represents the dimensions of an array, with each integer in the tuple indicating the size of the corresponding dimension.

In other words, integers at every index tell us how many items there are in the respective dimension.

According to the example above, index-6 has value 6, so 6th ( 5 + 1) dimension has 6 components.

Note: It is important to note that the shape tuple is simply a property of the Numpy array, and it does not control the actual size of the array.
Remember: The size of an array is determined by the number of elements contained in the array, while the shape of an array determines how those elements are organized along each dimension.

NumPy Array Reshape

In this section of article, we explore Numpy array reshape with examples in the expectation of fulfilling the learning aims.

The reshape() function in Numpy is used to change the shape of an array, allowing for a flexible representation of data.

This function takes two arguments: the first argument is the array that you want to reshape, and the second argument is the desired shape, which is specified as a tuple.

Reshape An Array

Numpy array reshape is the process of altering the shape of an array.

It is the number of items in each dimension that defines the shape of an array.

The user can insert or delete dimensions or modify the number of items in each dimension by reshaping.

Remember: The reshape() function returns a new array with the specified shape, and it does not modify the original array. If the number of elements in the original array is not equal to the number of elements in the new shape, the reshape() function will raise a ValueError.

Reshape From 1-D to 2-D

The following 1-D arrays has 7 components. Transform it into a 2-D array.

Example: 

import numpy as npy factorial_arr = npy.array([1, 2, 6, 24, 120, 720, 5040, 40320]) mrx_arr = factorial_arr.reshape(2, 4) print(mrx_arr)

In above example, we first import the Numpy library as npy for convenience. Then, we create a one-dimensional Numpy array named factorial_arr which contains the values of factorials from 1 to 8.

Next, we use the reshape() function on the factorial_arr array to change its shape from (8,) to (2, 4). This function returns a new array with the desired shape, which is stored in a new variable named mrx_arr.

Finally, we print the mrx_arr array using the print() function. The output of this code would be:

array([[    1,     2,     6,    24],
       [  120,   720,  5040, 40320]])  

As we can see, the mrx_arr array has been reshaped into a two-dimensional array with 2 rows and 4 columns.

The elements of the original array factorial_arr are rearranged in the new array to match the desired shape (2, 4).

Another Example: 

import numpy as npy palindrome_arr = npy.array(["wow", "peep", "rotator", "noon", "deed", "Madam ", "Civic", "Level"]) mrx_arr = palindrome_arr.reshape(2, 4) print(mrx_arr)

Reshape From 1-D to 3-D

The below code would output the following 3-dimensional reshaped array of the original 1-dimensional array:

Example: 

import numpy as npy factorial_arr = npy.array([1, 2, 6, 24, 120, 720, 5040, 40320]) mrx_arr = factorial_arr.reshape(2, 2, 2) print(mrx_arr)

Example: 

import numpy as npy palindrome_arr = npy.array(["wow", "peep", "rotator", "noon", "deed", "Madam ", "Civic", "Level"]) mrx_arr = palindrome_arr.reshape(2, 2, 2) print(mrx_arr)

In this example, we create a one-dimensional Numpy array named palindrome_arr which contains a list of palindrome words.

Next, we use the reshape() function on the palindrome_arr array to change its shape from (8,) to (2, 2, 2).

This function returns a new array with the desired shape, which is stored in a new variable named mrx_arr.

Finally, we print the mrx_arr array using the print() function.


What shapes can we reshape?

In our exploration of Numpy array reshape, it works, as long as the items required in both shapes are identical.

In a 1D array with 8 items, we can reshape it into a 2D array with 4 items in 2 rows, but not into a 3D array with 3 items in 3 rows.

You can transform a 1D array with 8 components into a 2D array with 3 items in each dimension by following these steps:

Example: 

import numpy as npy factorial_arr = npy.array([1, 2, 6, 24, 120, 720, 5040, 40320]) mrx_arr = factorial_arr.reshape(4, 3) print(mrx_arr)

Example: 

mport numpy as npy palindrome_arr = npy.array(["wow", "peep", "rotator", "noon", "deed", "Madam ", "Civic", "Level"]) mrx_arr = palindrome_arr.reshape(2, 6, 3) print(mrx_arr)

Find out whether the resulting array is a copy or a view:

Example: 

import numpy as npy factorial_arr = npy.array([1, 2, 6, 24, 120, 720, 5040, 40320]) print(factorial_arr.reshape(4, 2).base)

The code would output the base object of the reshaped array, which is the original 1-dimensional factorial_arr:

Example: 

import numpy as npy palindrome_arr = npy.array(["wow", "peep", "rotator", "noon", "deed", "Madam ", "Civic", "Level"]) print(palindrome_arr.reshape(4, 2).base)

In the above code, the original 1-dimensional palindrome_arr would be output as the base object of the reshaped array.

Unknown Dimension

One “unknown” dimension is permitted.

As we discussed with Numpy array reshape, you do not have to enter an accurate number for one of the dimensions.

NumPy will compute this number if you enter -1 as the value.

To transform an 8-element 1D array to a 2×2 3D array, follow the below examples:

Example: 

import numpy as npy factorial_arr = npy.array([1, 2, 6, 24, 120, 720, 5040, 40320]) mrx_arr = factorial_arr.reshape(2, 2, -1) print(mrx_arr)

Example: 

import numpy as npy palindrome_arr = npy.array(["wow", "peep", "rotator", "noon", "deed", "Madam ", "Civic", "Level"]) mrx_arr = palindrome_arr.reshape(2, 2, -1) print(mrx_arr)
Reminder: It is not possible to apply -1 to more than one dimension at a time.

Flattening arrays

Array flattening is the process of transforming a multidimensional array to a one-dimensional array utilizing Numpy.

To accomplish this, we can use reshape(-1).

Make the array one dimension by transforming it as follows:

Example: 

import numpy as npy evenOdd_arr = npy.array([[0, 2, 4, 6, 8 ,10], [1, 3, 5, 7, 9 , 11]]) mrx_arr = evenOdd_arr.reshape(-1) print(mrx_arr)

Example: 

import numpy as npy palindrome_arr = npy.array([["wow", "peep", "rotator", "noon"], ["deed", "Madam ", "Civic", "Level"]]) mrx_arr = palindrome_arr.reshape(-1) print(mrx_arr)
Reminder: Numpy offers a lot of functions for altering the shape of arrays flatten, ravel, and also for rearranging the items rot90, flip, fliplr, flipud, etc. In numpy, these are categorized under Basic to Expert.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *