NumPy: Get all 2D diagonals of a 3D numpy array
NumPy: Array Object Exercise-169 with Solution
Write a NumPy program to get all 2D diagonals of a 3D numpy array.
Sample Solution:
Python Code:
# Importing necessary libraries
import numpy as np
# Creating a 3D NumPy array with dimensions 3x4x5 using arange and reshape methods
np_array = np.arange(3 * 4 * 5).reshape(3, 4, 5)
# Printing the original 3D NumPy array and its type
print("Original NumPy array:")
print(np_array)
print("Type: ", type(np_array))
# Extracting 2D diagonals from the 3D array with the specified axes using np.diagonal
result = np.diagonal(np_array, axis1=1, axis2=2)
# Printing the 2D diagonals and their type
print("\n2D diagonals: ")
print(result)
print("Type: ", type(result))
Sample Output:
Original Numpy array: [[[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] [[20 21 22 23 24] [25 26 27 28 29] [30 31 32 33 34] [35 36 37 38 39]] [[40 41 42 43 44] [45 46 47 48 49] [50 51 52 53 54] [55 56 57 58 59]]] Type: <class 'numpy.ndarray'> 2D diagonals: [[ 0 6 12 18] [20 26 32 38] [40 46 52 58]] Type: <class 'numpy.ndarray'>
Explanation:
np_array = np.arange(3*4*5).reshape(3,4,5)
In the above code -
- np.arange(3*4*5) generates a 1D array of integers from 0 to (345)-1, which is from 0 to 59.
- reshape(3, 4, 5) reshapes the 1D array into a 3D array with dimensions 3x4x5.
- rp_array stores the created 3D array.
result = np.diagonal(np_array, axis1=1, axis2=2): This code computes the diagonal elements of the 3D array along the specified axes (axis1 and axis2). In this case, the diagonals are taken along the 2nd (axis1=1) and 3rd (axis2=2) dimensions of the array. For each element along the first dimension, the function picks the diagonal elements from the 4x5 sub-arrays. ‘result’ variable stores the computed diagonal elements.
Pictorial Presentation:
Python-Numpy Code Editor:
Previous: Write a NumPy program to convert Pandas dataframe to Numpy array with headers.
Next: Create a 2-dimensional array of size 2 x 3, composed of 4-byte integer elements. Write a NumPy program to find the number of occurrences of a sequence in the said 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/python-numpy-exercise-169.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics