w3resource

Numpy program to Transpose and add arrays


NumPy: Broadcasting Exercise-7 with Solution


Given a 2D array of shape (3, 5) and a 1D array of shape (3,). Write a Numpy program that transposes the 2D array and add the 1D array to each row of the transposed array.

Sample Solution:

Python Code:

import numpy as np

# Initialize the 2D array of shape (3, 5)
array_2d = np.array([[1, 2, 3, 4, 5],
                     [6, 7, 8, 9, 10],
                     [11, 12, 13, 14, 15]])

# Initialize the 1D array of shape (3,)
array_1d = np.array([1, 2, 3])

# Transpose the 2D array to get shape (5, 3)
transposed_array = np.transpose(array_2d)

# Add the 1D array to each row of the transposed array
# Broadcasting is used here to add 1D array to each row of transposed 2D array
result_array = transposed_array + array_1d

# Display the result
print(result_array)

Output:

[[ 2  8 14]
 [ 3  9 15]
 [ 4 10 16]
 [ 5 11 17]
 [ 6 12 18]]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Initializing arrays: Two arrays are initialized, one 2D array of shape (3, 5) and one 1D array of shape (3,).
  • Transposing the 2D array: The 2D array is transposed to get a new shape of (5, 3).
  • Broadcasting and Addition: The 1D array is added to each row of the transposed array using broadcasting.
  • Displaying result: The resulting array is printed out.

Python-Numpy Code Editor: