Professional Documents
Culture Documents
Operations
Advanced array broadcasting techniques
Applying mathematical operations on arrays using broadcasting
On Day 20, we will dive deeper into Array Broadcasting and Advanced Operations in
NumPy. Broadcasting allows you to perform operations on arrays with different shapes,
making your code more concise and efficient. Let's explore advanced broadcasting
techniques and apply mathematical operations on arrays using broadcasting:
# Create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Broadcasted Addition:")
print(row_addition)
Broadcasted Addition:
[[11 22 33]
[14 25 36]]
# Create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Scalar Multiplication:")
print(scalar_multiplication)
Scalar Multiplication:
[[ 2 4 6]
[ 8 10 12]]
# Create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Squared Array:")
print(squared_array)
Squared Array:
[[ 1 4 9]
[16 25 36]]
In these examples:
🌐 Real-World Scenario:
1.Image Processing:
Use Case: Performing image manipulation and enhancement.
NumPy Application: Broadcasting allows you to apply various operations to the
individual color channels of an image efficiently.
Example: You have a color image represented as a NumPy array with shape (height,
width, 3), where the last dimension corresponds to the red, green, and blue color
channels. To increase the brightness of the image, you can easily multiply each
channel by a brightness factor using broadcasting. This brightens the image without
the need for explicit loops or channel-wise operations.
Let's dive into an example of how broadcasting can be applied for image
manipulation:
plt.subplot(1, 2, 2)
plt.title("Brightened Image")
plt.imshow(brightened_image)
plt.axis('off')
plt.show()
Suppose you have a lidar data array with shape (N, 2) representing (x,
y) coordinates and a radar data array with shape (N, 3) representing
(x, y, z) coordinates. You want to transform the lidar data to include
height (z) information.
You have historical price data for each asset in the portfolio. To calculate VaR, you need to
perform a matrix operation on the asset returns and weights. Broadcasting simplifies this
process.
# Portfolio value
portfolio_value = 1000000 # $1,000,000