What is broadcasting in NumPy?
a) The ability to perform operations on arrays of different shapes
b) The process of flattening a multidimensional array
c) The method of copying data between arrays
d) The technique of merging multiple arrays into one
Answer:
a) The ability to perform operations on arrays of different shapes
Explanation:
Broadcasting in NumPy refers to the ability to perform operations on arrays of different shapes by automatically expanding the smaller array’s dimensions to match the larger array’s shape. This allows for efficient vectorized operations without the need for explicit looping.
import numpy as np
# Creating a 2D array and a 1D array
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
arr2 = np.array([1, 2, 3])
# Broadcasting the 1D array across the 2D array
result = arr1 + arr2
print(result)
In this example, the 1D array arr2
is broadcasted across the 2D array arr1
, allowing for element-wise addition.
Broadcasting is a powerful feature in NumPy, enabling concise and efficient array operations, even when the arrays involved have different shapes.