f. c.
f. c.

Reputation: 1145

How to set certain True elements to False in a boolean array in python?

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')

Upvotes: 2

Views: 1841

Answers (2)

GZ0
GZ0

Reputation: 4268

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

a[idx[~b]] = False

Upvotes: 2

wasif
wasif

Reputation: 15518

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])

Upvotes: 1

Related Questions