w3resource

Numpy Program to reshape and add 1D arrays using Broadcasting


Write a NumPy program that creates two 1D arrays x of shape (5,) and y of shape (5,). Reshape them to (5, 1) and (1, 5) respectively, and perform element-wise addition using broadcasting.

Sample Solution:

Python Code:

import numpy as np

# Initialize two 1D arrays of shape (5,)
x = np.array([1, 2, 3, 4, 5])
y = np.array([10, 20, 30, 40, 50])

# Reshape the arrays to (5, 1) and (1, 5) respectively
x_reshaped = x.reshape((5, 1))
y_reshaped = y.reshape((1, 5))

# Perform element-wise addition using broadcasting
result_array = x_reshaped + y_reshaped

# Display the result
print(result_array)

Output:

[[11 21 31 41 51]
 [12 22 32 42 52]
 [13 23 33 43 53]
 [14 24 34 44 54]
 [15 25 35 45 55]]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Initializing arrays: Two 1D arrays of shape (5,) are initialized.
  • Reshaping arrays: The arrays are reshaped to (5, 1) and (1, 5) respectively to enable broadcasting.
  • Broadcasting and Addition: Element-wise addition is performed using broadcasting between the reshaped arrays.
  • Displaying result: The resulting array is printed out.

Python-Numpy Code Editor: