How to extract the upper values from the whole 3D array in python

Viewed 810

Is it possible to extract the upper values from the whole 3D array? A simple example of a 3D array is below:

import numpy as np

a = np.array([[[7, 4, 2], [5, 0, 4], [0, 0, 5]],
               [[7, 6, 1], [3, 9, 5], [0, 8, 7]],
               [[8, 10, 3], [1, 2, 15], [9, 0, 1]]]) 
2 Answers

You can use the numpy building-matrices functions like numpy.triu (triangle-upper) or numpy.tril (triangle-lower) to return a copy of a matrix with the elements above or below the k-th diagonal zeroed.

If, on the other hand, you are only interested in the values ​​above or below the diagonal (without having a copy of the matrix), you can simply use numpy.triu_indices and numpy.tril_indices, as follows:

upper_index = np.triu_indices(n=3, k=1)

where n is the size of the arrays for which the returned indices will be valid, and k the diagonal offset.

and return the indices for the triangle. The returned tuple contains two arrays, each with the indices along one dimension of the array:

(array([0, 0, 1], dtype=int64), array([1, 2, 2], dtype=int64))

now you can use the indexes obtained as indexes of your array and you will get:

a[upper_index]

and gives:

array([[5, 0, 4],
       [0, 0, 5],
       [0, 8, 7]])

Similarly you can find the part under the diagonal using numpy.tril_indices.

IUUC, You could use triu_indices:

result = a[np.triu_indices(3)]
print(result)

Output

[[7 4 2]
 [5 0 4]
 [0 0 5]
 [3 9 5]
 [0 8 7]
 [9 0 1]]

If you want those strictly above the diagonal, you can pass an offset value:

result = a[np.triu_indices(3, 1)]
print(result)

Output

[[5 0 4]
 [0 0 5]
 [0 8 7]]
Related