NumPy is a popular Python library used for scientific computing. It provides a powerful N-dimensional array object, which is the core of many scientific computing tasks. The shape of a NumPy array is an important attribute that describes the size of the array in each dimension. In this article, we will explore the NumPy array shape and its various properties.
The shape of a NumPy array is a tuple of integers that describes the size of the array in each dimension. For example, a 2-dimensional array with 3 rows and 4 columns has a shape of (3, 4). The shape attribute of a NumPy array can be accessed using the shape property. Here is an example:
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr.shape)
The output of this code will be:
(2, 3)
This means that the array has 2 rows and 3 columns.
The shape of a NumPy array can be changed using the reshape() method. This method returns a new array with the same data but a different shape. Here is an example:
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) new_arr = arr.reshape(2, 3) print(new_arr) print(new_arr.shape)
The output of this code will be:
[[1 2 3] [4 5 6]] (2, 3)
This means that the original array has been reshaped into a 2-dimensional array with 2 rows and 3 columns.
Here are some more code examples that demonstrate the properties of NumPy array shape:
The ndim property returns the number of dimensions of the array:
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) print(arr.ndim)
The output of this code will be:
1
This means that the array has 1 dimension.
The size property 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)
The output of this code will be:
6
This means that the array has 6 elements.
The flatten() method returns a 1-dimensional copy of the array:
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) new_arr = arr.flatten() print(new_arr) print(new_arr.shape)
The output of this code will be:
[1 2 3 4 5 6] (6,)
This means that the original 2-dimensional array has been flattened into a 1-dimensional array with 6 elements.
The transpose() method returns a new array with the axes transposed:
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) new_arr = arr.transpose() print(new_arr) print(new_arr.shape)
The output of this code will be:
[[1 4] [2 5] [3 6]] (3, 2)
This means that the original 2-dimensional array has been transposed into a new array with 3 rows and 2 columns.
In this article, we have explored the NumPy array shape and its various properties. We have seen how to access the shape attribute of a NumPy array, how to change the shape of an array using the reshape() method, and how to use other methods like ndim, size, flatten(), and transpose(). NumPy array shape is an important concept in scientific computing, and understanding it is essential for working with NumPy arrays.