w3resource

Numpy program to Transpose and add arrays


7. Transpose and Add 1D Array to Each Row

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.

For more Practice: Solve these Related Problems:

  • Transpose a given 2D array and then add a 1D array to each row using broadcasting, verifying the new shape.
  • Create a function that adds a constant vector to the transposed array and then transposes it back to the original layout.
  • Implement a solution that compares the result of transposing and adding with the result of adding and then transposing.
  • Test the operation on arrays with different dimensions to ensure broadcasting applies correctly to rows.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Divide columns of 2D array by 1D array using NumPy Broadcasting.
Next: Numpy Program to subtract 1D array from 2D slices of 3D array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.