NumPy - Array Shape

NumPy Array Shape

The shape of a NumPy array is a tuple of integers. Each integer in the tuple represents the size of the array along a particular dimension or axis. For example, an array with shape (3, 4) has 3 rows and 4 columns.

  • For a 2D array, the shape is a tuple with two elements: number of rows, number of columns.
  • For a 3D array, the shape is a tuple with three elements: depth, number of rows, number of columns.
  • Higher-dimensional arrays follow the same pattern, with each dimension’s size represented as an additional element in the tuple.

Accessing Array Shape

You can access the shape of a NumPy array using the shape attribute. This attribute returns a tuple of integers, each representing the size of the array along a particular dimension.

Example

In the following example, we are creating a 2D array and retrieving its shape using the NumPy “shape” attribute −

import numpy as np

# Creating a 2D array
array = np.array([[1, 2, 3], [4, 5, 6]])

# Accessing the shape
print("Shape of the array:", array.shape)
print("Number of dimensions:", array.ndim)
print("Total number of elements:", array.size)

The shape (2, 3) indicates that the array has 2 rows and 3 columns. It is a two-dimensional array −

Shape of the array: (2, 3)
Number of dimensions: 2
Total number of elements: 6

Changing Array Shape

Changing the shape of a NumPy array refers to transforming the dimensions of an array without altering its data. For instance, a one-dimensional array can be reshaped into a two-dimensional array or vice versa, as long as the total number of elements remains constant.

To reshape an array in NumPy, we use the reshape() function. This function returns a new view of the array with the specified shape if possible. If the reshape is not possible with a view, a copy of the array is created.

Example

In this example, we are changing the shape of a 2D array to 1D array by passing “-1” as an argument to the Numpy reshape() function. This automatically infer the size of one dimension −

import numpy as np

# Creating a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("Original 2D array:\n", array_2d)

# Reshaping to a 1D array
array_flattened = array_2d.reshape(-1)
print("Flattened to 1D array:", array_flattened)

This will produce the following result −

Original 2D array:
[[1 2 3]
 [4 5 6]]
Flattened to 1D array: [1 2 3 4 5 6]

Handling Reshape Errors

Sometimes reshaping arrays in NumPy can lead to errors if not used correctly. This error occurs when you attempt to reshape an array into a shape that is incompatible with the total number of elements in the array.

The total number of elements must remain constant when reshaping. If the reshape operation is incompatible with the total number of elements, NumPy will raise a ValueError.

Example: Incompatible Shape Error

The incompatible shape error occurs when you attempt to reshape an array into a shape that is incompatible with the total number of elements in the array.

In the example below, the original array has “12” elements. Reshaping it into a shape “(3, 5)” requires 15 elements, which causes a ValueError −

import numpy as np

# Creating an array with 12 elements
array = np.arange(12)

# Attempting to reshape into a shape that requires more elements
try:
   reshaped_array = array.reshape((3, 5))
except ValueError as e:
   print("Error:", e)

Following is the output of the above code −

Error: cannot reshape array of size 12 into shape (3,5)

Example: Negative Dimension Error

Using -1 in the reshape dimensions tells NumPy to automatically calculate the size of that dimension. However, if the remaining dimensions don’t align with the total number of elements, it will raise an error −

import numpy as np

# Creating an array with 10 elements
array = np.arange(10)

# Attempting to reshape with an incompatible automatic dimension
try:
   reshaped_array = array.reshape((2, -1, 4))
except ValueError as e:
   print("Error:", e)

The output obtained is as shown below −

Error: cannot reshape array of size 10 into shape (2,newaxis,4)

Example: Incorrect Dimension Specification

Specifying an incorrect or non-integer dimension value (e.g., a negative value other than -1, or a non-integer) can lead to errors −

import numpy as np

# Creating an array with 16 elements
array = np.arange(16)

# Attempting to reshape with an invalid dimension
try:
   reshaped_array = array.reshape((4, 4.5))
except ValueError as e:
   print("Error:", e)

After executing the above code, we get the following output −

Traceback (most recent call last):
  File "/home/cg/root/669f5fd83ed84/main.py", line 8, in <module>
reshaped_array = array.reshape((4, 4.5))
TypeError: 'float' object cannot be interpreted as an integer
© 2024 All rights reserved. | Made With 🤍 By The_MAK Team