2

I have two boolean arrays a and b. The number of True elements in a is equal to the length of the array b, like this:

import numpy as np
a = np.array([0, 1, 0, 1, 0, 0, 0, 1], dtype='bool')
b = np.array([1,1,0], dtype='bool')

I know that I can use np.where(a)[0] to find the indices of True elements in a:

idx = np.where(a)[0]

And I have idx:

array([1, 3, 7])

Now according to b

array([1, 1, 0])

I want to keep the first two True values in a to be True, and flip the last True value to False. That is to say, to flip the value of a[7] to 0 and keep the rest of values in a:

res = np.array([0, 1, 0, 1, 0, 0, 0, 0])

How to do it in a python way? Suppose I have a long array of a and a relative short b. The False values in b are not necessarily to be the last one, could happen anywhere and multiple times, so b could also be

b = np.array([0,1,0], dtype='bool')

2 Answers 2

2

Just use b to select the indices that needs to be set to False.

a[idx[~b]] = False
Sign up to request clarification or add additional context in comments.

Comments

1

Use negative indexing with np.where:

a[np.where(a)[0][-1]]=0

Your array as integer values:

array([0, 1, 0, 1, 0, 0, 0, 0])

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.