﻿ NumPy: Get all 2D diagonals of a 3D numpy array - w3resource # 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:

``````import numpy as np
np_array = np.arange(3*4*5).reshape(3,4,5)
print("Original Numpy array:")
print(np_array)
print("Type: ",type(np_array))
result = np.diagonal(np_array, axis1=1, axis2=2)
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'>
```

Pictorial Presentation: Python Code Editor:

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

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

﻿

## Python: Tips of the Day

List comprehension:

```>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]
```