Pineapples - 3 months ago 8
Python Question

# If X and Y matches element in NumPy Array

How do I check if there is an element in an array where both axes

`[X, Y]`
match
`[drawx, drawy]`
?

I have a NumPy array:

``````#format: [X, Y]
wallxy = numpy.array([[0,1],[3,2],[4,6]])
``````

and two other variables:

``````#attached to a counter that increases value each loop
drawx = 3
drawy = 2
``````

I'm using the array as a set of positions
`[[0,1],[3,2],[4,6]]`
and I need to test if
`[drawx, drawy]`
(also representing a position) is in one of the positions on both the X and Y axis etc.
`drawx = 4`
`drawy = 6`
returns true
`drawx = 3`
`drawy = 2`
returns true
`drawx = 4`
`drawy = 2`
returns false
`drawx = 2`
`drawy = 1`
returns false

`==` will broadcast the comparison, so

``````wallxy = numpy.array([[0, 1],[3, 2][4, 6]])
z0 = numpy.array([3,2])
z1 = numpy.array([2,3])

(z0==wallxy).all(1).any()  # True
(z1==wallxy).all(1).any()  # False
``````

Which is, I think, what you're looking for.

Printing out the intermediate steps will be useful to understanding and working out similar tasks:

``````z0 == wallxy     # checks which elements match
#  array([[False, False],
#         [ True,  True],
#         [False, False]], dtype=bool)

(z0==wallxy).all(1)   # checks whether all elements of axis 1 match
#  array([False,  True, False], dtype=bool)

(z0==wallxy).all(1).any()   # checks whether any axis 1 matches z0
#  True
``````

If instead you used `z0 = numpy.array([2,3])`, then everything would be `False`.

Source (Stackoverflow)