1

I have an array of N-dimensional values arranged in a 2D array. Something like:

import numpy as np
data = np.array([[[1,2],[3,4]],[[5,6],[1,2]]])

I also have a single value x that I want to compare against each data point, and I want to get a 2D array of boolean values showing whether my data is equal to x.

x = np.array([1,2])

If I do:

data == x

I get

# array([[[ True,  True],
#        [False, False]],
#
#       [[False, False],
#        [ True,  True]]], dtype=bool)

I could easily combine these to get the result I want. However, I don't want to iterate over each of these slices, especially when data.shape[2] is larger. What I am looking for is a direct way of getting:

array([[ True,  False],
        [False, True]])

Any ideas for this seemingly easy task?

2
  • Hmm. Just realized that my answer gives a 2-d array as a result, while your question gives a 3-d array as the desired output. Is that distinction important? Commented May 2, 2012 at 17:09
  • No that's perfect, thanks. I will amend my desired output. Commented May 2, 2012 at 18:30

1 Answer 1

2

Well, (data == x).all(axis=-1) gives you what you want. It's still constructing a 3-d array of results and iterating over it, but at least that iteration isn't at Python-level, so it should be reasonably fast.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.