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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/numpy-program-to-transpose-and-add-arrays.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics