1

I have an array which I want to use boolean indexing on, with multiple index arrays, each producing a different array. Example:

w = np.array([1,2,3])
b = np.array([[False, True, True], [True, False, False]])

Should return something along the lines of:

[[2,3], [1]]

I assume that since the number of cells containing True can vary between masks, I cannot expect the result to reside in a 2d numpy array, but I'm still hoping for something more elegant than iterating over the masks the appending the result of indexing w by the i-th b mask to it.

Am I missing a better option?

Edit: The next step I want to do afterwards is to sum each of the arrays returned by w[b], returning a list of scalars. If that somehow makes the problem easier, I'd love to know as well.

4
  • Are you looking for elegance or performance? Those two aren't the same. Commented Nov 30, 2019 at 17:27
  • If you are looking to just get the summations, simply use matrix-multiplication - b.dot(w). Commented Nov 30, 2019 at 17:30
  • I would use dot product (I'm imitating that), but in my real example both b and w are very large and sparse, where b is known to only contain 1s. I'm going for performance here. Commented Nov 30, 2019 at 17:32
  • If those are stored in regular arrays and not sparse matrices, the dot product should still be pretty fast. Commented Nov 30, 2019 at 17:36

2 Answers 2

1

Assuming you want a list of numpy arrays you can simply use a comprehension:

w = np.array([1,2,3])
b = np.array([[False, True, True], [True, False, False]])
[w[bool] for bool in b]

# [array([2, 3]), array([1])]

If your goal is just a sum of the masked values you use:

np.sum(w*b) # 6

or

np.sum(w*b, axis=1) # array([5, 1])
# or b @ w

…since False times you number will be 0 and therefor won't effect the sum.

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

Comments

0

Try this:

[w[x] for x in b]

Hope this helps.

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.