1

I have an items array which has shape (n, 3), and a counts array which has the same shape (n, 3). How can I make every C in items to have count = 0 without resorting to loops?

items = np.array([['B', 'A', 'C'],
    ['B', 'B', 'C'],
    ['A', 'B', 'A'],
    ['C', 'C', 'C'],
    ['B', 'B', 'B']])

counts = np.array([[1, 3, 2],
    [4, 2, 3],
    [2, 2, 1],
    [3, 2, 1],
    [1, 2, 1]])

Expected output:

>>> counts
np.array([[1, 3, 0],
    [4, 2, 0],
    [2, 2, 1],
    [0, 0, 0],
    [1, 2, 1]])

1 Answer 1

3

What you're looking for is:

counts[items == 'C'] = 0

A more explicit way to express it is:

c_indices = np.where(items == 'C')
counts[c_indices] = 0
Sign up to request clarification or add additional context in comments.

2 Comments

There is no good reason to use where for this. It is longer, slower, consumes more memory, and in my opinion less legible. +1 for how to construct the mask though.
I can't believe it's that simple. Oh well

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.