NumPy: Get all 2D diagonals of a 3D numpy array
Extract all 2D diagonals of a 3D array.
Write a NumPy program to get all 2D diagonals of a 3D numpy array.
Sample Solution:
Python Code:
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:
For more Practice: Solve these Related Problems:
- Write a NumPy program to extract the main 2D diagonal from each 2D slice of a 3D array using np.diagonal.
- Create a function that iterates over the first axis of a 3D array and returns an array of all 2D diagonals.
- Implement a solution that uses list comprehension to gather diagonals from each 2D sub-array and stacks them into a 2D array.
- Test the diagonal extraction on a 3D array with non-uniform sub-array sizes to ensure robustness.
Go to:
PREV : Convert Pandas DataFrame to NumPy array with headers.
NEXT : Count occurrences of sequences in a 2D array.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.