Essential Tools for Array Manipulation: Examples using numpy.shape()
Import NumPy
You'll typically begin by importing the NumPy library usingimport numpy as np
. This establishes thenp
alias to access NumPy functions and attributes conveniently.Create a NumPy Array
Arrays are the fundamental data structure in NumPy. You can create arrays using thenp.array()
function. For instance, to create a 2D array:arr = np.array([[1, 2, 3], [4, 5, 6]])
Get the Array Shape
Once you have your NumPy array, use the.shape
attribute to retrieve its shape. This attribute returns a tuple representing the number of elements along each dimension of the array.shape = arr.shape
Interpreting the Shape
The returned tuple provides insights into the array's dimensionality. In the case of a 2D array, the shape might be(2, 3)
, indicating there are 2 rows (first element) and 3 columns (second element) in the array.
import numpy as np
# Create a 3D array
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
# Get the shape of the array using numpy.shape()
shape = arr.shape
# Print the shape of the array
print(shape)
This code will output:
(2, 2, 3)
The output(2, 2, 3)
signifies that the array has a shape of 2 (number of rows in the 3D array), 2 (number of columns in each sub-array within the 3D array), and 3 (number of elements in each row/column).
Reshaping arrays
import numpy as np
# Create a 1D array
arr = np.array([1, 2, 3, 4, 5, 6])
# Print the original shape
print("Original shape:", arr.shape)
# Reshape the array into a 2x3 matrix (requires compatible total number of elements)
reshaped_arr = arr.reshape(2, 3)
# Print the reshaped array and its shape
print("Reshaped array:\n", reshaped_ arr)
print("Shape after reshape:", reshaped_arr.shape)
This code showcases how numpy.shape()
helps verify if a reshape operation is possible (compatible total elements) and displays the resulting shape after the reshape.
Element-wise operations
import numpy as np
# Create two arrays with compatible shapes
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.array([[7, 8, 9], [10, 11, 12]])
# Print the shapes of both arrays
print("Shape of arr1:", arr1.shape)
print("Shape of arr2:", arr2.shape)
# Perform element-wise addition (requires matching shapes)
sum_arr = arr1 + arr2
# Print the resulting array
print("Sum of arrays:\n", sum_arr)
Here, numpy.shape()
ensures the arrays have compatible shapes before performing element-wise addition. If the shapes don't match, NumPy will raise an error.
Broadcasting
import numpy as np
# Create a 1D array and a 2D array
arr1 = np.array([1, 2, 3])
arr2 = np.array([[10, 20, 30], [40, 50, 60]])
# Print the shapes of both arrays
print("Shape of arr1:", arr1.shape)
print("Shape of arr2:", arr2.shape)
# Perform addition using broadcasting (arr1 is expanded to match arr2)
sum_arr = arr1 + arr2
# Print the resulting array
print("Sum using broadcasting:\n", sum_arr)
In this example, numpy.shape()
helps understand how broadcasting works. Even though arr1
has a different shape, NumPy expands it to match arr2
element-wise for the addition operation.
Using len() for 1D arrays
- If you're dealing with a guaranteed 1D array and only need the total number of elements, you can use the built-in
len()
function. However, this won't provide information about the shape along different dimensions likenumpy.shape()
does.
import numpy as np # Create a 1D array arr = np.array([1, 2, 3, 4]) # Get the total number of elements using len() total_elements = len(arr) # Get the shape using numpy.shape() shape = arr.shape print("Total elements using len():", total_elements) print("Shape using numpy.shape():", shape)
This code demonstrates that
len()
only returns the single value (4 in this case), whereasnumpy.shape()
returns the complete shape tuple(4,)
.- If you're dealing with a guaranteed 1D array and only need the total number of elements, you can use the built-in
Attribute Access for Number of Dimensions
- To retrieve the total number of dimensions (ranks) in an array, you can use the
ndim
attribute of the array.
import numpy as np # Create a 3D array arr = np.array([[[1, 2, 3]]]) # Get the number of dimensions using ndim num_dimensions = arr.ndim # Get the shape using numpy.shape() shape = arr.shape print("Number of dimensions:", num_dimensions) print("Shape using numpy.shape():", shape)
Here,
arr.ndim
returns 3, indicating a 3D array, whilearr.shape
provides the complete shape information(1, 1, 3)
.- To retrieve the total number of dimensions (ranks) in an array, you can use the