[[+content_image]]
D
D
Daniil Shevkunov2021-06-26 13:25:44
Python
Daniil Shevkunov, 2021-06-26 13:25:44

How to get from a three-dimensional numpy array the strings that match the specified one?

I have a numpy array:
a = np.array([, ])

Another kind

([[[1, 0, 0],
[2, 0, 1],
[2, 0, 2]],

[[0, 0, 0],
[2, 0, 3],
[0, 0, 0]]])


I need to get all the strings that match the string [2, 0, 2], more precisely, I would like to get an array of the form
[[False, False, True], [False, False, False]]

how to do this without a loop?

PS - by the way, in the Python section, this is the 28000th question)

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
V
Vindicar, 2021-06-26
@danila763

(a == [2,0,2]).all(axis=2)
a == [2,0,2] will give you a three-dimensional array of boolean values ​​- the result of an element-by-element comparison, while the comparison will be on the last dimension.
all(axis=2) will group this array by the third dimension, with the group being true only if all values ​​in the group are true. Those. only if all values ​​in this line matched.

>>> a = np.array([[[1, 0, 0], [2, 0, 1], [2, 0, 2]], [[0, 0, 0], [2, 0, 3], [0, 0, 0]]])
>>> a == [2,0,2]
array([[[False,  True, False],
        [ True,  True, False],
        [ True,  True,  True]],

       [[False,  True, False],
        [ True,  True, False],
        [False,  True, False]]])
>>> (a == [2,0,2]).all(axis=2)
array([[False, False,  True],
       [False, False, False]])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question