Skip to main content

Introduction to Python NumPy Array Shape

Python NumPy Array Shape

The shape of an array refers to the dimensions and sizes of each dimension of the array.

It provides information about the structure and organization of the array data. The shape of an array is represented as a tuple of integers, where each integer represents the size of a specific dimension.

Here are a few ways to access and manipulate the shape of a NumPy array:

Accessing the Shape

The shape attribute of an array can be used to access its shape.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape) # Output: (2, 3)

In the example above:

  • The shape of arr is (2, 3), indicating that it has 2 rows and 3 columns.

Changing the Shape

The shape of an array can be changed using the reshape() method. This method returns a new array with the desired shape.

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape((2, 3))
print(reshaped_arr.shape) # Output: (2, 3)

In the example above:

  • The original 1-dimensional array arr is reshaped to a 2-dimensional array with the shape (2, 3).

Size of the Array

The size attribute of an array returns the total number of elements in the array.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.size) # Output: 6

In the example above, the array arr has a size of 6, indicating that it contains 6 elements.