Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

python - "In" operator for numpy arrays?

How can I do the "in" operation on a numpy array? (Return True if an element is present in the given numpy array)

For strings, lists and dictionaries, the functionality is intuitive to understand.

Here's what I got when I applied that on a numpy array

a
array([[[2, 3, 0],
    [1, 0, 1]],

   [[3, 2, 0],
    [0, 1, 1]],

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

   [[1, 3, 0],
    [2, 0, 1]],

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

b = [[3, 2, 0],
    [0, 1, 1]]

b in a
True
#Aligned with the expectation

c = [[300, 200, 0],
    [0, 100, 100]]

c in a
True
#Not quite what I expected
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could compare the input arrays for equality, which will perform broadcasted comparisons across all elements in a at each position in the last two axes against elements at corresponding positions in the second array. This will result in a boolean array of matches, in which we check for ALL matches across the last two axes and finally check for ANY match, like so -

((a==b).all(axis=(1,2))).any()

Sample run

1) Inputs :

In [68]: a
Out[68]: 
array([[[2, 3, 0],
        [1, 0, 1]],

       [[3, 2, 0],
        [0, 1, 1]],

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

       [[1, 3, 0],
        [2, 0, 1]],

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

In [69]: b
Out[69]: 
array([[3, 2, 0],
       [0, 1, 1]])

2) Broadcasted elementwise comparisons :

In [70]: a==b
Out[70]: 
array([[[False, False,  True],
        [False, False,  True]],

       [[ True,  True,  True],
        [ True,  True,  True]],

       [[False,  True,  True],
        [False,  True,  True]],

       [[False, False,  True],
        [False, False,  True]],

       [[ True, False,  True],
        [ True, False,  True]]], dtype=bool)

3) ALL match across last two axes and finally ANY match :

In [71]: (a==b).all(axis=(1,2))
Out[71]: array([False,  True, False, False, False], dtype=bool)

In [72]: ((a==b).all(axis=(1,2))).any()
Out[72]: True

Following similar steps for c in a -

In [73]: c
Out[73]: 
array([[300, 200,   0],
       [  0, 100, 100]])

In [74]: ((a==c).all(axis=(1,2))).any()
Out[74]: False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...